c语言实现回调函数
2016-06-04 10:13
489 查看
callback.c
运行结果
[root@centos6 data]# gcc callback.c
[root@centos6 data]# ./a.out
test1:
不调用回调函数打印:hello world!!
回调 functionA(char *str) 函数:hello world!!
test1:
不调用回调函数打印:hello world!!
回调 functionB(char *str) 函数:hello world!!
test2:
不调用回调函数打印:hello world!!
回调 functionA(char *str) 函数:hello world!!
test2:
不调用回调函数打印:hello world!!
回调 functionB(char *str) 函数:hello world!!
test3:
回调 functionB(char *str) 函数:hello world!!
始于2012-10-05,Tencent;更新至2016-06-04,杭州。
/* * @file c语言实现回调函数 * @detial 在java等更高级的语言中往往已经给我们封装好了回调函数的调用方式,直接用就可以了。 * 而C语言中并没有这种直接可以操作的回调方式,我们用函数指针来实现回调原理。 */ #include<stdio.h> // 将函数名作为指针的格式为:int (*ptr)(char *p) 即:返回值(指针名)(参数列表) typedef int (*callback)(char *str); // 回调函数的名称为 callback,参数是char *p // functionA的格式符合 callback 的格式,因此可以看作是一个 callback类型 int functionA(char *str) { printf("回调 functionA(char *str) 函数:%s!\n", str); return 0; } // functionB的格式符合 callback 的格式,因此也可以看作是一个 callback类型 int functionB(char *str) { printf("回调 functionB(char *str) 函数:%s!\n", str); return 0; } // 调用回调函数,方式一:通过命名方式 int test1(callback p_callback, char *str) { printf("test1:\n不调用回调函数打印:%s!\n", str); p_callback(str); return 0; } // 调用回调函数,方式二:直接通过函数指针 int test2(int (*ptr)(), char *str) { printf("test2:\n不调用回调函数打印:%s!\n", str); (*ptr)(str); } int main() { char *str = "hello world!"; test1(functionA, str); test1(functionB, str); test2(functionA, str); test2(functionB, str); printf("test3:\n"); callback test3 = functionB; test3(str); return 0; }
运行结果
[root@centos6 data]# gcc callback.c
[root@centos6 data]# ./a.out
test1:
不调用回调函数打印:hello world!!
回调 functionA(char *str) 函数:hello world!!
test1:
不调用回调函数打印:hello world!!
回调 functionB(char *str) 函数:hello world!!
test2:
不调用回调函数打印:hello world!!
回调 functionA(char *str) 函数:hello world!!
test2:
不调用回调函数打印:hello world!!
回调 functionB(char *str) 函数:hello world!!
test3:
回调 functionB(char *str) 函数:hello world!!
始于2012-10-05,Tencent;更新至2016-06-04,杭州。
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- 如何写好 C main 函数
- Lua和C语言的交互详解
- C#中异步回调函数用法实例
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法
- C语言自动生成enum值和名字映射代码
- C语言练习题:自由落体的小球简单实例
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中进制知识汇总
- C语言中计算正弦的相关函数总结
- 使用C语言详解霍夫曼树数据结构
- C语言实现选择排序、冒泡排序和快速排序的代码示例