探讨C语言中的回调函数

Posted by jintang on 2012-09-12

回调函数是一个程序员不能显式调用的函数;
通过将回调函数的地址传给调用者从而实现调用。

回调函数使用是必要的,在我们想通过一个统一接口实现不同的内 容,这时用回掉函数非常合适。

比如,我们为几个不同的设备分别写了不同的显示函数:

1
void TVshow(); void ComputerShow(); void NoteBookShow()

等等。这是我们想用一个统一的显示函数,我们这时就可以用回掉函数了。

void show(void (*ptr)()); 使用时根据所传入的参数不同而调用不同的回调函数。

不同的编程语言可能有不同的语法,下面举一个c语言中回调函数的例子,其中一个回调函数不带参数,另一个回调函数带参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//Test.c
#include
#include

int Test1()
{
int i;
for (i=0; i<30; i++)
{
printf("The %d th charactor is: %c\n", i, (char)('a' + i%26));
}
return 0;
}

int Test2(int num)
{
int i;
for (i=0; i
{
printf("The %d th charactor is: %c\n", i, (char)('a' + i%26));
}
return 0;
}

/**
* 指向函数的指针作函数参数
*/
void Caller1(void (*ptr)())
{
(*ptr)();
}

/**
* 指向函数的指针作函数参数
* 这里第一个参数是为指向函数的指针服务的,
* 不能写成void Caller2(int (*ptr)(int n)),这样的定义语法错误。
*/
void Caller2(int n, int (*ptr)())
{
(*ptr)(n);
return;
}

int main()
{
printf("************************\n");
Caller1(Test1); //相当于调用Test2();
printf("&&&&&&************************\n");
Caller2(30, Test2); //相当于调用Test2(30);
return 0;
}