标签:
内核中使用了大量的用c语言实现的对象
尤其是驱动中,基本上都是这种架构
这里写一个小例子,模仿内核中编程的方法
代码如下:
root@ubuntu:/mnt/shared/appbox/funcptr# cat funcptr.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> typedef struct { char *name; int (*write)(char *); int (*read)(char *); }FuncPtrSt; FuncPtrSt funcptr_ops; int funcptr_write(char *str) { printf("func:%s, line:%d, str:%s\n", __FUNCTION__,__LINE__, str); return 0; } int funcptr_read(char *str) { printf("func:%s, line:%d, str:%s\n", __FUNCTION__,__LINE__, str); return 0; } int funcptr_init(FuncPtrSt *fops) { fops->name = (char *)malloc(sizeof(32)); if(fops->name == NULL) { printf("malloc failed!\n"); return -1; } strcpy(fops->name, "funcptr"); fops->write = funcptr_write; fops->read = funcptr_read; return 0; } int funcptr_probe(FuncPtrSt *fops) { printf("fops->name:%s\n", fops->name); fops->write("write test!\n"); fops->read("read test!\n"); return 0; } int main(int argc, char *argv) { funcptr_init(&funcptr_ops); funcptr_probe(&funcptr_ops); return 0; }
root@ubuntu:/mnt/shared/appbox/funcptr# ./funcptr fops->name:funcptr func:funcptr_write, line:17, str:write test! func:funcptr_read, line:23, str:read test!
标签:
原文地址:http://blog.csdn.net/xiangpingli/article/details/42131817