分享

原来C语言也可以面向对象(一)

 写意人生 2014-06-28

C语言是一门博大精深的语言,我相信没有研读过Linux中代码的人,很少有人体会到吧,废话不多说,简单的写了一个测试demo


test.h

  1. typedef void (* func1_callback)(void);  
  2. typedef void (* func2_callback)(int i);  
  3.   
  4. typedef struct {  
  5.     int size;  
  6.     func1_callback func1_cb;  
  7.     func2_callback func2_cb;  
  8.       
  9. } testCallback;  
  10.   
  11. typedef struct {  
  12.     int size;  
  13.     int (*init)(testCallback *_tcb);  
  14.     int (*set)(int i);  
  15.     int (*release)(void);  
  16. } testInterface;  

test.c

  1. #include "test.h"  
  2. #include <stdio.h>  
  3.   
  4. testCallback tcb;  
  5.   
  6. int test_init(testCallback *_tcb) {  
  7.     printf("This is test init function.\n");  
  8.     tcb = *_tcb;      
  9.     tcb.func1_cb();  
  10.     return 0;  
  11. }  
  12.   
  13. int test_set(int i) {  
  14.     printf("This is test set function, argumaent i is : %d\n", i);    
  15.     tcb.func2_cb(i);  
  16.     return 0;  
  17. }  
  18.   
  19. int test_release(void) {  
  20.     printf("This is test release function.\n");   
  21.     return 0;  
  22. }  
  23.   
  24. static const testInterface tInterface = {  
  25.     .size = sizeof(testInterface),  
  26.     .init = test_init,  
  27.     .set = test_set,  
  28.     .release = test_release,      
  29. };  
  30.   
  31. const testInterface *get_test_interface() {  
  32.     return &tInterface;   
  33. }  

main.c

  1. #include "test.h"  
  2. #include <stdio.h>  
  3. void func1_cb() {  
  4.     printf("This is func1 cb, has no argument.\n");   
  5. }  
  6.   
  7. void func2_cb(int i) {  
  8.     printf("This is func2 cb, argument i is : %d\n", i);  
  9. }  
  10.   
  11. testCallback tcb = {  
  12.     sizeof(testCallback),  
  13.     func1_cb,  
  14.     func2_cb,     
  15. };  
  16.   
  17. static const testInterface *ti;  
  18.   
  19. int main(void) {  
  20.     ti = get_test_interface();  
  21.     ti->init(&tcb);  
  22.     ti->set(10);  
  23.     ti->release();  
  24.   
  25.     return 0;  
  26. }  

这个测试demo很简单,不用解释了吧,这篇先这样了。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多