回调函数:假设A是回调函数,B是调用者,B参数里一个是指向A的函数指针,即回调A,同时另外的参数传递给A作为参数。A可以是多个函数的统一指向,只要函数参数一致即可。
WINDOWS回调函数:永远不会被程序中的其他函数或子程序调用。只能由操作系统调用。因此,windows可以通过传递不同参数给回调函数达到和程序沟通的目的。
那么:B调用A,A也有参数,有参数就要赋值才行。所以B函数内部给A参数赋值。B调用A,A又利用了B给的参数。
A就是回调函数。B就是调用者。
#include<stdio.h>
#include<stdlib.h>
int (*ptr)(char *p);//函数指针的格式为,返回值类型 (*指针名)(参数列表)
typedef int (*pFunCallBack)(char *p); //利用类型定义,给函数指针类型取个别名/外号,注:利用类型定义有利于程序的移植
int Afun(char *p)
{
printf("Afun 回调打印出字符%s!\n", p);
return 0;
}
int Cfun(char *p)
{
printf("Cfun 回调打印:%s, Nice to meet you!\n", p);
return 0;
}
/*下面的这些是调用者:有几种方式*/
//方式1
int call1(pFunCallBack pCallBack, char *p)
{
pCallBack(p);
return 0;
}
//方式2
int call2(char *p, pFunCallBack pCallBack)
{
pCallBack(p);
return 0;
}
//方式3
int call3(int (*ptr)(char *),char *p)
{
(*ptr)(p);
return 0;
}
//方式4
int call4(char *p, int (*ptr)(char *))
{
(*ptr)(p);
return 0;
}
//验证小结的第三点结论,详细验证,相信你可以
void myFun(int a,int b)
{
int t;
t = a + b;
printf("a + b = %d\n",t);
}
void call(int a,int b,int c,void (*pFun)(int a,int b))
{
pFun(b,c);
}
int main()
{
char *p = "hello";
printf("***********调用方式1*************\n");
call1(Afun, p); //调用Afun回调函数,传递参数*P给Afun函数
call1(Cfun, p); //调用Cfun回调函数,传递参数*P给Afun函数
printf("\n\n");
printf("***********调用方式2*************\n");
call2(p, Afun); //调用Afun回调函数,传递参数*P给Afun函数
call2(p, Cfun); //调用Cfun回调函数,传递参数*P给Afun函数
printf("\n\n");
printf("***********调用方式3*************\n");
call3(Afun,p); //调用Afun回调函数,传递参数*P给Afun函数
call3(Cfun,p); //调用Cfun回调函数,传递参数*P给Afun函数
printf("\n\n");
printf("***********调用方式4*************\n");
call4(p, Afun); //调用Afun回调函数,传递参数*P给Afun函数
call4(p, Cfun); //调用Cfun回调函数,传递参数*P给Afun函数
call(1,2,3,myFun);
system("pause");
return 0;
}
/*
小结:
* 函数指针的格式为,返回值类型 (*指针名)(参数列表)
* 调用函数声明函数指针的参数可采取两种方式,一种是直接定义,另外一种是利用typedef
* 回调函数的参数的传递由调用函数来传递(之所以叫回调的原因就在于此,调用函数调用被调函数,被调函数又需要获取调用者的参数)
传递的参数要么都在函数指针前或要么都在函数指针后,且都要紧挨着函数指针,且参数的类型及顺序要正确
*/