在学习Linux内核的时候,我们经常会发现它里面的好多思想是借鉴像Java,C++等高级语言的面向对象。不过,我们都知道,Linux内核的编写基本都是用C语言实现的(其中包含内联的汇编),同时,我们也知道,C语言是典型的面向过程语言,它是怎么实现面向对象的呢?
Linux内核的开发人员都是绝顶聪明的人,他们利用C语言的结构体,并在结构体中建立函数指针的字段,就好像C++中的所有字段都是 public,由此,实现了面向对象的思想。
下面,我写了一段测试代码,实现C语言的面向对象,如下所示:
/** * @author DLUTBruceZhang * 2013.8.23 */ #include<stdio.h> #include<string.h> struct apple { char *color; float weight; float price; void (*buy)(struct apple ale); }; void buy_apple(struct apple ale); int main(void) { struct apple MyApple; MyApple.color = (char*)malloc(sizeof(char) * 10); strcpy(MyApple.color, "red"); MyApple.weight = 0.15; MyApple.price = 1.5; MyApple.buy = buy_apple; MyApple.buy(MyApple); free(MyApple.color); printf("\n"); printf("You konw, this is C's OOP !\n"); } void buy_apple(struct apple ale) { printf("Today I buy a %s apple, it %f kg, it costs me %f $ .", ale.color, ale.weight, ale.price); }
由此可见,我在 struct apple 结构体中嵌入 buy 函数指针,它返回空,且包含有三个参数,我在主函数中给它传递函数定义的地址,并最后调用结构体的函数指针字段。同时,程序中使用一个技巧,给函数指针的参数时这个结构体本身,这是因为,毕竟 C 语言不是面向对象的,所以它不能得到父结构体中的各个字段,它仍需要结构体原型。