Bootstrap

回调函数和函数指针用法

最近与公司大佬交流过程学习到新的知识再次记录:https://www.runoob.com/w3cnote/c-callback-function.html
函数指针和回调函数用法如下,在此仅做记录:
1、函数指针类型:函数返回值类型 (* 指针变量名) (函数参数列表);
例如:
用法1:

int(*p)(int, int);            //声明函数指针
int Max(int x, int y);      //定义Max函数
c = (*p)(a, b);              //通过函数指针调用Max函数

用法2,添加结构体回调函数:


typedef struct
{
	int (*func1)(void);					//不带参数回调函数
	int (*func2)(int a,int b);	//带参数回调函数
	
}FUN;

FUN	function;

int cabllback1(void)
{
	static int a=1,b=1;
	a++;
	b++;
	printf("回调函数值1: %d  %d\r\n",a,b);
	return (a+b);
}

int cabllback2(int a, int b)
{
	printf("回调函数值2: %d  %d\r\n",a,b);
	return (a+b);
}

int main()
{
	func1Value = function.func1();
	printf("func1Value = %d\r\n",func1Value);
		
	func2Value = function.func2(1,2);
	printf("func2Value = %d\r\n",func2Value);
}

2、回调函数无参数:

int Callback_1()    // 回调函数
{
    printf("Hello, this is Callback_1 ");
    return 0;
}

int Handle(int (*Callback)())  //输入函数句柄
{
    Callback();
}

int main(1)
{
  Handl1e(Callback_1);    //主函数调用回调函数方法
}

3、回调函数带参数:

int Callback_1(int x) // 回调函数
{
    printf("Hello, this is Callback_1: x = %d ", x);
    return 0;
}

int Handle(int y, int (*Callback)(int))    //回调函数句柄
{
    printf("Entering Handle Function. ");
    Callback(y);
    printf("Leaving Handle Function. ");
}

int main()
{
    int a = 123;
    Handle(a, Callback_1);
    return 0;
}

 

 

;