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 2021-12-23 17:16 Hello-World3 阅读(282) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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