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

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很简单,不用解释了吧,这篇先这样了。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值