C/C++ struct 的回调函数使用技巧

回调函数是一个通过函数指针调用的函数。如果你把函数指针(函数的入口地址)传递给另一个函数,当这个函数指针被用来调用它所指向的函数时,我们就说这个函数是回调函数。可以作为函数参数传递哦。

使用struct 回调函数可以使得代码更加清晰明了

话不多说上代码:

1.定义回调函数的原型


typedef int STRU_FU;

STRU_FU sfun1(int a, const char *b){

	printf("fun1  a = %d , b = %s \n",a,b);

	return a;
}

STRU_FU sfun2(int a, void *b,float c){

	printf("fun2  a = %d , b = %f \n",a,c);

	return a;
}

STRU_FU sfun3(int a, char b,long c){

	printf("fun3  a = %d , *b = %ld \n",a,c);
	return a;
}

2. 定义的struct的回调函数

struct fun_ops{ //定义回调函数struct

	STRU_FU (*fun1)(int a, char *b); //注册参数
	STRU_FU (*fun2)(int a, void *b,float c);
	STRU_FU (*fun3)(int a, char b,long c);
};

3. 注册回调函数

struct fun_ops fuops = {//注册初始化函数指针的函数

	.fun1 = sfun1,
	.fun2 = sfun2,
	.fun3 = sfun3,
};

4.完整的代码

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

typedef int STRU_FU;

STRU_FU sfun1(int a, const char *b){

	printf("fun1  a = %d , b = %s \n",a,b);

	return a;
}

STRU_FU sfun2(int a, void *b,float c){

	printf("fun2  a = %d , b = %f \n",a,c);

	return a;
}

STRU_FU sfun3(int a, char b,long c){

	printf("fun3  a = %d , *b = %ld \n",a,c);
	return a;
}

struct fun_ops{ //定义回调函数struct

	STRU_FU (*fun1)(int a, char *b); //注册参数
	STRU_FU (*fun2)(int a, void *b,float c);
	STRU_FU (*fun3)(int a, char b,long c);
};

struct fun_ops fuops = {//初始化函数指针的函数

	.fun1 = sfun1,
	.fun2 = sfun2,
	.fun3 = sfun3,
};

int main(int argc,  char* argv[])
{
	int g;
	struct fun_ops *ops = NULL;

	if(argc < 2)

	{
		printf("please input 1 or 2 or 3 for test fun \n");
		return -1;
	}

	if(strcmp(argv[1], "1") == 0)
	{
		ops = &fuops;//赋值结构体
		g =1;
		printf("fun1 \n");
		ops->fun1(111,"fun1");//调用回调
	}else if( !strcmp(argv[1], "2")){

		ops = &fuops;
		g= 2;
		printf("fun2 \n");
		ops->fun2(2222,"fun2",3333);

	}else{

		ops = &fuops;
		g = 3;
		printf("fun3 \n");
		ops->fun3(1212,"y",9999999);

	}
	}

猜你喜欢

转载自blog.csdn.net/yang_quan_yang/article/details/106049288