天天看点

手把手教你写回调函数

                                        手把手教你写回调函数

手把手教你写回调函数

手把手教你写回调函数源代码

回调函数的主要功能就是提供统一的接口以及事件的通知。如果你是从事middleware,框架,提供api编程的,那么你肯定少不了要使用回调函数。

所谓提供统一接口或者事件的通知即:当发生某一事件或者出现某一个状态之后必定会进行某种操作。但是这个操作又不能写死,不同的环境不同的程序会有不同的实现,也就是说提供接口的人不想把逻辑写死,而是由调用接口的人来实现逻辑。这也就是回调函数的主要功能。

回调函数,唯一途径就是传递函数指针。通过这个函数指针来调用真正的函数。

下面使用代码说明究竟如何实现回调函数,并通过这个例子来说明回调函数的作用:

/**

filename: mytimer.h

description:

这里我用一个闹钟静态库mytimer.a来演示回调函数的实现方法

*/

#ifndef mytimer_h

#define mytimer_h

typedef void (*tmfun)(tumfun );

typedef struct{

tmfun t_fun;

}tmhandle;

static tmhandle tmstruct;

extern void starttimer(int intercal);

extern void registtimer(tumfun f);

filename: mytimer.c

name: registtimer

注册闹钟处理函数。由于闹钟时间到之后,不同的人处理函数不同

所以,这里只提供接口,并不实现处理函数逻辑。

调用接口者需要自己实现处理函数,并注册启动闹钟

void registtimer(tmfun f){

tmstruct.t fun = f;

}

name; starttimer

根据参数设定时间并启动定时器

void starttimer(int interval){

int tmpi = 0;

int fixtim = 500000000;

int tmpfix = 0;

for(tmpi;tmpi<=interval;tmpi++)

for(tmpfix;tmpfix<=fixtim*2;tmpfix++);

(*tmstruct.t_fun)();

以上是静态库的全部代码

linux下输入以下命令制作动态库:

$ gcc -c mytimer.c

$ ar -rc libmytimer.a mytimer.o

测试程序:

filename: testtimer.c

description:

对接口进行测试,调用静态库

#include <stdio.h>

#include <unistd.h>

#include "mytimer.h"

name:handler

description:闹钟处理函数,即回调函数

void handle(){

printf("hi legend, i am a callback/n");

int main(int argc, char **argv){

registtimer(&handle);//对闹钟处理函数进行注册

starttimer(5);

return 0;

将上面静态库头文件mytimer.h, libmytimer.a和testtimer.c放到同一个文件夹下面

然后输入以下命令:

$ gcc -o testtimer -l./ testtimer.c -lmytimer

然后得到的testtimer就是可执行程序。

手把手教你写回调函数

手把手教你写回电函数源代码

版权申明:

转载文章请注明原文出处http://blog.csdn.net/feiyinzilgd/archive/2010/12/31/6110811.aspx

并请联系谭海燕本人或者前往谭海燕个人主页留言

继续阅读