C函數適配器

來源:互聯網
上載者:User

普通變數可以通過指標進行訪問,用起來很方便,現在我有個想法,就是玩函數也要玩的這麼炫,我想給它寫個適配器……

這裡我主要是用可變參數和函數指標來實現,有兩個測試程式碼片段:test1()和test2()。其中test1用的是可變參數的函數指標,test2用的是宏實現的函數適配器。

代碼如下:

 1 /*
2 File : adapter.c
3 Author : Mike
4 E-Mail : Mike_Zhang@live.com
5 */
6 #include <stdio.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <stdarg.h>
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跑不過,用的時候注意點。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.