先来说说函数
int func(int x); /* 声明一个函数 */
int (*f) (int x); /* 声明一个函数指针 */
f=func; /* 将func函数的首地址赋给指针f */
例子:
#include <stdio.h>
//#include "windows.h"
int (__cdecl *myCallBackFun)(int Param1,int Param2);<----指针(函数用法)
int mymax(int a,int b){
return a>b?a:b;
}
int main()
{
int *p; <----指针(普通用法)
int a=10;
p=&a; <------指向变量(普通用法)
int b=20;
int c=0;
c=mymax(a,b);
printf("%d/n",c);
myCallBackFun=mymax;<-----指向函数(函数用法)
printf("%d/n",c);
return 0;
}
其实都是一样的用法,只是内容变了!大家多多对比学习!
再讲讲回调函数看代码:
#include <stdio.h>
typedef void (*callback_t)(void *);
void repeat_three_times(callback_t, void *);
void repeat_three_times(callback_t f, void *para)<-----函数作为参数
{
f(para);
f(para);
f(para);
}
void say_hello(void *str)
{
printf("Hello %s/n", (const char *)str);
}
void count_numbers(void *num)
{
int i;
for(i=1; i<=(int)num; i++)
printf("%d ", i);
putchar('/n');
}
int main(void)
{
repeat_three_times(say_hello, "Guys");<-----把函数作为参数
repeat_three_times(count_numbers, (void *)4);<-----把函数作为参数
return 0;
}
运行结果如下:
Hello Guys
Hello Guys
Hello Guys
1 2 3 4
1 2 3 4
1 2 3 4
Press any key to continue
回调函数:如果参数是一个函数指针,调用者(say_hello,count_numbers)可以传递一个函数的地址给实现者(repeat_three_times),让实现者(repeat_three_times)去调用它,这称为回调函数(Callback Function)。
在GUI编程中异步回调函数更是有普遍的应用,例如为某个按钮注册一个回调函数,当用户点击按钮时调用它。(自己对照vb,vc,delphi的按钮控件运行框架看看,是不是回调呢?)
callback函数 DlgProc = yC.0040290E
汇编中的回调函数
DlgProc proc hDlg:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM
(假设)对应c版本函数
BOOL CALLBACK MyDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_INITDIALOG:
return TRUE;
case WM_DESTROY:
EndDialog(hDlg, 0);
return TRUE;
}
return FALSE;
}
在回调函数中对应着消息处理函数,我就不多说了。可以参考Windows的消息处理函数
LRESULT CALLBACK WindowProc(
HWND hwnd, // handle of window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);