Linux驱动中继承与多态思想_C

一、函数实现多态

1. 定义全局模板函数集

复制代码
//thermal_of.c
static struct thermal_zone_device_ops of_thermal_ops = {
    .get_trip_type = of_thermal_get_trip_type,
    .get_trip_temp = of_thermal_get_trip_temp,
    .set_trip_temp = of_thermal_set_trip_temp,
    .get_trip_hyst = of_thermal_get_trip_hyst,
    .set_trip_hyst = of_thermal_set_trip_hyst,
    .get_crit_temp = of_thermal_get_crit_temp,

    .bind = of_thermal_bind,
    .unbind = of_thermal_unbind,
};
复制代码

2. 使用时继承全局模板函数集

//thermal_of.c
int __init of_parse_thermal_zones(void)
{
    ...
    struct thermal_zone_device_ops *ops = kmemdup(&of_thermal_ops, sizeof(*ops), GFP_KERNEL);
    ...
}

kmemdup 就是先分配一块内存,然后直接拷贝过去一份,拷贝的都是指针,这样既可以复用原来的,也可以修改为自己的,实现多态。

 

二、结构体多态

1. 参考binder.c

复制代码
//参考内核中binder.c的 struct binder_object 的实现

struct object_header {
    int    type;
};

struct student_object {
    struct object_header hdr;
    int grade;
    int score;
}

struct teacher_object {
    struct object_header hdr;
    int rank;
    int suject;
}

struct worker_object {
    struct object_header hdr;
    int salary;
    int hour;
}

//实现结构体多态
struct people_object {
    union {
        struct object_header hdr; //复用这个hdr,可以省去一个int型空间
        struct student_object so;
        struct teacher_object to;
        struct worker_object wo;
    };
};

//处理多态
void dump_mesage(struct people_object *obj) {
    switch (obj->hdr.type) {
    case 1:
        printf("student: grade=%d, score=%d\n", obj->so.grade, obj->so.score);
    case 1:
        printf("teacher: rank=%d, suject=%d\n", obj->to.rank, obj->to.suject);
    case 1:
        printf("worker: salary=%d, hour=%d\n", obj->wo.salary, obj->wo.hour);
    default:
        break;
    }
    
}
复制代码

有了执行hdr的指针后,可以统一使用 container_of() 来得到各个类型指针。

 

posted on   Hello-World3  阅读(282)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2018-12-23 网卡驱动_WDS

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示