C语言 — 函数的注册和回调
函数注册和回调函数
1、什么是函数注册和回调
回调函数无非是对函数指针的应用,说白了就是通过使用函数指针来调用一个函数,而函数注册就是把函数指针作为参数传递出去便于别的模块使用的过程。所以函数注册就是为了回调,先注册再回调。
2、为什么要使用回调函数
回调函数可以把调用者与被调用者分开,所以调用者不关心谁是被调用者以及被调用者如何实现。它只需知道存在一个具有特定原型和限制条件的被调用函数。简而言之,回调函数就是允许用户把需要调用的方法的指针作为参数传递给一个函数,以便该函数在处理相似事件的时候可以灵活的使用不同的方法。
3、回调函数常见应用场景
不同模块由不同开发人员实现,为了实现模块间信息交互触发行为。(似乎很难理解,下面看模型吧)
3、函数注册和回调的模型
模块A用来实现出现各种事件后的函数处理,程序B 用来监控发生的事件。A模块向B模块注册函数,B模块监控到事件后回调事件的函数处理。
直接上代码:
//test.h 头文件#include <stdio.h>#include <string.h>#include <stdlib.h>#include <sys/types.h>typedef void (*pf_callbakck)(int a);typedef struct Compute_ST{int index;pf_callbakck function;}Compute_ST;int Registe_Callback_Fun(Compute_ST *registed_fun);void mgmtb_fun(int num);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*A Module*//*TestA.c 文件
实现回调函数*/#include 'test.h'void callback_fun(int event){switch(event){case 1:{printf('ABCDEFG.\n');}break;case 2:{printf('abcdefg.\n');}break;case 3:{printf('1234567.\n');}break;case 4:{printf('7654321.\n');}break;default:{printf('New event, %d.\n',event);}}}void main(){int event = 0;Compute_ST ptr_compute;ptr_compute.index = 1;ptr_compute.function = callback_fun;//注册回调函数if(-1 == Registe_Callback_Fun(&ptr_compute)){printf('Registe failed.\n');}for(;;){printf('Enter number:');scanf('%d', &event);if(event == 0){return;}//触发事件mgmtb_fun(event);}return;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636412345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
/*B Module testB.c文件 实现注册函数 实现事件触发回调*/#include 'test.h'pf_callbakck g_ptrfun;int Registe_Callback_Fun(Compute_ST *registed_fun){if(1 != registed_fun->index){printf('Registe failed.\n');return -1;} g_ptrfun = registed_fun->function;}void mgmtb_fun(int event){g_ptrfun(event);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
把上面三个文件放在同一个目下编译
[root@localhost home]# gcc testA.c testB.c -o test.exe [root@localhost home]# ./test.exe Enter number:3 1234567. Enter number:2 abcdefg. Enter number:1 ABCDEFG.1234567812345678
赞 (0)
