回调函数
[定义]回调函数就是一个通过函数指针调用的函数。如果函数A的指针(地址)作为参数传递给函数C,当函数A的指针被用于调用函数A时,我们就说函数A是一个回调函数。回调函数不是由该函数的实现方称为函数A直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
1 使用回调函数可以将调用者和被调用者分开,所以调用者不关心谁是被调用者。它只需知道存在一个具有特定原型和限制条件的被调用函数。
2 回调函数本质上是为了解决异步操作
[应用]
1 当某个鼠标事件发生的时候自动调用
2 创建一个线程,线程开始运行时,执行注册的函数操作
3 QT类似的槽信号(slot-signal)机制,当某个信号signal发生时,调用相应的槽函数slot
4 用于通知机制,与信号槽类似
函数A中设置一个计时器,每到一定时间,该函数会得到相应的通知,但通知机制的实现者对程序一无所知。那么,就需一个具有特定原型的函数指针进行回调,通知函数A事件已经发生。实际上,API使用一个回调函数SetTimer()来通知计时器。如果没有提供回调函数,它还会把一个消息发往程序的消息队列。
给个例子便于理解
#include <stdio.h>
#include <stdlib.h>
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
printf("%d and %d\n", numberSource(), numberSource());
}
/* A possible callback */
int overNineThousand(void) {
return (rand() % 1000) + 9001;
}
/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(&rand);
PrintTwoNumbers(&overNineThousand);
PrintTwoNumbers(&meaningOfLife);
return 0;
}
[参考]
http://www.cppblog.com/converse/archive/2010/04/19/113023.html
http://en.wikipedia.org/wiki/Callback_(computer_programming)
转载请注明:http://blog.youkuaiyun.com/u012606927/article/details/18005791