码迷,mamicode.com
首页 > 其他好文 > 详细

示例:模拟内核中的面向对象方法

时间:2014-12-25 00:17:10      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

内核中使用了大量的用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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!