Skip to main content
 首页 » 编程设计

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

2022年07月19日20kenshinobiy

一、函数实现多态

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() 来得到各个类型指针。


本文参考链接:https://www.cnblogs.com/hellokitty2/p/15724411.html