C语言中的回调函数

来源:互联网 发布:会计软件中的成本核算 编辑:程序博客网 时间:2024/04/28 13:16

C语言中通过函数指针实现回调函数(Callback Function)


====== 首先使用typedef定义回调函数类型 ====== 

[cpp] view plaincopyprint?
  1. typedef void (*event_cb_t)(const struct event *evt, void *userdata);  
上面的语句表示event_cb_t类型函数范围值类型为void类型。


====== 定义并实现一个函数用于注册回调函数 ======

[cpp] view plaincopyprint?
  1. int event_cb_register(event_cb_t cb, void *userdata);  

下面是注册回调函数my_event_cb的一个模板

[cpp] view plaincopyprint?
  1. static void my_event_cb(const struct event *evt, void *data)  
  2. {  
  3.     /* do stuff and things with the event */  
  4. }  
  5.   
  6. ...  
  7.    event_cb_register(my_event_cb, &my_custom_data);  
  8. ...  

在事件调度器(event dispatcher)中,常常将回调函数放在结构体中,

[cpp] view plaincopyprint?
  1. struct event_cb {  
  2.     event_cb_t cb;  
  3.     void *data;  
  4. };  
此时通过访问结构体成员变量调用回调函数

[cpp] view plaincopyprint?
  1. struct event_cb *callback;  
  2.   
  3. ...  
  4.   
  5. /* Get the event_cb that you want to execute */  
  6.   
  7. callback->cb(event, callback->data);  


====== 一个回调函数的例子 ======

[cpp] view plaincopyprint?
  1. #include <stdio.h>  
  2.   
  3. struct event_cb;  
  4.   
  5. typedef void (*event_cb_t)(const struct event_cb *evt, void *user_data);  
  6.   
  7. struct event_cb  
  8. {  
  9.     event_cb_t cb;  
  10.     void *data;  
  11. };  
  12.   
  13. static struct event_cb saved = { 0, 0 };  
  14.   
  15. void event_cb_register(event_cb_t cb, void *user_data)  
  16. {  
  17.     saved.cb = cb;  
  18.     saved.data = user_data;  
  19. }  
  20.   
  21. static void my_event_cb(const struct event_cb *evt, void *data)  
  22. {  
  23.     printf("in %s\n", __func__);  
  24.     printf("data1: %s\n", (const char *)data);  
  25.     printf("data2: %s\n", (const char *)evt->data);  
  26. }  
  27.   
  28. int main(void)  
  29. {  
  30.     char my_custom_data[40] = "Hello!";  
  31.     event_cb_register(my_event_cb, my_custom_data);  
  32.   
  33.     saved.cb(&saved, saved.data);  
  34.   
  35.     return 0;  
  36. }
0 0
原创粉丝点击