博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C函数适配器
阅读量:7112 次
发布时间:2019-06-28

本文共 1402 字,大约阅读时间需要 4 分钟。

普通变量可以通过指针进行访问,用起来很方便,现在我有个想法,就是玩函数也要玩的这么炫,我想给它写个适配器……

这里我主要是用可变参数和函数指针来实现,有两个测试代码片段:test1()和test2()。其中test1用的是可变参数的函数指针,test2用的是宏实现的函数适配器。

代码如下:

1 /*  2 File      : adapter.c  3 Author    : Mike  4 E-Mail    : Mike_Zhang@live.com  5 */  6 #include 
7 #include
8 #include
9 #include
10 11 #define adapter(f,...) f(__VA_ARGS__) 12 typedef int(*fun)(int a,...); 13 14 int fun1(int a,int b) 15 {
16 return a+b; 17 } 18 19 int fun2(int a,char *str) 20 {
21 return a+strlen(str); 22 } 23 24 int fun3(int a,char *str,long l) 25 {
26 return a+strlen(str)+l; 27 } 28 29 void test1() 30 {
31 int a = 10,b = 2; 32 fun p; 33 34 printf("test1\n"); 35 36 p = (fun)fun1; 37 printf("%d\n",p(a,b)); 38 p = (fun)fun2; 39 printf("%d\n",p(a,(char*)"just a test")); 40 p = (fun)fun3; 41 printf("%d\n",p(a,(char*)"just a test",1)); 42 } 43 44 void test2() 45 {
46 int a = 10,b = 2; 47 fun p; 48 49 printf("test2\n"); 50 51 p = (fun)fun1; 52 printf("%d\n",adapter(p,a,b)); 53 p = (fun)fun2; 54 printf("%d\n",adapter(p,a,"just a test")); 55 p = (fun)fun3; 56 printf("%d\n",adapter(p,a,"just a test",1)); 57 } 58 59 int main() 60 {
61 test1(); 62 test2(); 63 return 0; 64 }

tips : gcc和VS2010都行,VC6跑不过,用的时候注意点。

转载地址:http://ywmhl.baihongyu.com/

你可能感兴趣的文章
Cocos2dx学习笔记(2) string char* int类型数据转换
查看>>
我的友情链接
查看>>
python 数据结构 tree 的插入和遍历
查看>>
Linux学习时遇到的问题5
查看>>
虚拟桌面发展的下一个里程碑,构建在CWC之上的软件定义工作空间
查看>>
Map,Map.Entry<K,V>源码分析
查看>>
看<连城诀>有感
查看>>
VTK隐函数之vtkPlane
查看>>
3、Juniper SSG550M STATUS状态灯呈红色(内存条问题)
查看>>
Docker学习——三大组件【镜像、容器、仓库】的应用(二)
查看>>
mysql原理详解及部署
查看>>
taokeeper 架设与部署
查看>>
IIS配置Sencha touch
查看>>
elasticsearch文档-analysis
查看>>
拦截请求返回值的方法
查看>>
我的编程之路
查看>>
yum软件包详解
查看>>
安装hadoop和配置hadoop,启动namenode和设置免密登录的详细解析!
查看>>
Spark Streaming:大规模流式数据处理
查看>>
解决Spring Cloud中Feign/Ribbon第一次请求失败的方法
查看>>