ResourceFrom:http://lemote.blog.163.com/blog/static/1748395072013111631216547/
软件模块之间总是存在着一定的接口,从调用方式上,可以把他们分为三类:同步调用、回调和异步调用。同步调用是一种阻塞式调用,调用方要等待对方执 行完毕才返回,它是一种单向调用;回调是一种双向调用模式,也就是说,被调用方在接口被调用时也会调用对方的接口;异步调用是一种类似消息或事件的机制,不过它的调用方向刚好相反,接口的服务在收到某种讯息或发生某种事件时,会主动通知客户方(即调用客户方的接口)。回调和异步调用的关系非常紧密,通常我们使用回调来实现异步消息的注册,通过异步调用来实现消息的通知。
回调函数也是一个函数或过程,不过它是一个由调用方自己实现,供被调用方使用的特殊函数。回调函数可以象普通函数一样被程序调用,但是只有它被当作参数传递给被调函数时才能称作回调函数。如果被调函数被赋了不同的值给该参数,那么调用者将调用不同地址的函数。赋值可以发生在运行时,这样使你能实现动态绑定。
C语言:
- typedef int (*CallBackFun) (char *p);//定义函数类型
- int Afun(char *p) {return 0;}
- int call(CallBackFun pCallBack, char *p){pCallBack(p); return 0;}
- int call2(char *p, int (*ptr)()) {(*ptr)(p); return 0;}//函数指针
typedef int (*CallBackFun) (char *p);//定义函数类型
int Afun(char *p) {return 0;}
int call(CallBackFun pCallBack, char *p){pCallBack(p); return 0;}
int call2(char *p, int (*ptr)()) {(*ptr)(p); return 0;}//函数指针
- //调用:
- char *p = "hello";
- call(Afun,p);
- call2(p,Afun);
//调用:
char *p = "hello";
call(Afun,p);
call2(p,Afun);
C语言的标准库函数中很多地方就采用了回调函数来让用户定制处理过程。如常用的快速排序函数、二分搜索函数等。
举例:
- #include <stdio.h>
- #include <stdlib.h>
- int list[5]= {54, 21, 11, 67, 22};
- int sort_fucntion(const void *a, const void *b);
- int main(int argc, const char * argv[])
- {
- qsort((void *)list, 5, sizeof(list[0]), sort_fucntion);
- for (int x = 0; x < 5; x++) {
- printf("%i\n", list[x]);
- }
- return 0;
- }
- int sort_fucntion(const void *a, const void *b)
- {
- return *(int *)a - *(int *)b;//由小到大排序
- //return *(int *)b - *(int *)a;//由大到小排序
- }
#include <stdio.h>
#include <stdlib.h>
int list[5]= {54, 21, 11, 67, 22};
int sort_fucntion(const void *a, const void *b);
int main(int argc, const char * argv[])
{
qsort((void *)list, 5, sizeof(list[0]), sort_fucntion);
for (int x = 0; x < 5; x++) {
printf("%i\n", list[x]);
}
return 0;
}
int sort_fucntion(const void *a, const void *b)
{
return *(int *)a - *(int *)b;//由小到大排序
//return *(int *)b - *(int *)a;//由大到小排序
}
Xcode运行结果:
P.S.:
qsort函数原型:
void qsort (void * base, size_t num, size_t size, int (*compar) (const void *, const void *));
bsearch函数原型:
void * bsearch (const void * key, const void * base, size_t num, size_t size, int (*compar) (const void *, const void *));
详细用法请戳:http://www.cplusplus.com/reference/cstdlib/qsort/?kw=qsort
http://blog.csdn.net/wuming22222/article/details/39345705