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

来源:互联网 发布:sql 多表查询结果合并 编辑:程序博客网 时间:2024/04/27 14:39

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


test.h

typedef void (* func1_callback)(void);typedef void (* func2_callback)(int i);typedef struct {int size;func1_callback func1_cb;func2_callback func2_cb;} testCallback;typedef struct {int size;int (*init)(testCallback *_tcb);int (*set)(int i);int (*release)(void);} testInterface;

test.c

#include "test.h"#include <stdio.h>testCallback tcb;int test_init(testCallback *_tcb) {printf("This is test init function.\n");tcb = *_tcb;tcb.func1_cb();return 0;}int test_set(int i) {printf("This is test set function, argumaent i is : %d\n", i);tcb.func2_cb(i);return 0;}int test_release(void) {printf("This is test release function.\n");return 0;}static const testInterface tInterface = {.size = sizeof(testInterface),.init = test_init,.set = test_set,.release = test_release,};const testInterface *get_test_interface() {return &tInterface;}

main.c

#include "test.h"#include <stdio.h>void func1_cb() {printf("This is func1 cb, has no argument.\n");}void func2_cb(int i) {printf("This is func2 cb, argument i is : %d\n", i);}testCallback tcb = {sizeof(testCallback),func1_cb,func2_cb,};static const testInterface *ti;int main(void) {ti = get_test_interface();ti->init(&tcb);ti->set(10);ti->release();return 0;}

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

原创粉丝点击