Linux内核基础-container_of

/**

* cont     ai   ner_of - cast a member of a structure out to the containing structure

* @ptr: the poin     te   r to the member.

* @type: the type of the container struct this is embedded in.

* @member: the name of the member within the struct.

*

*/

#define container_of(ptr, type, member) ({ \

const typeof( ((type *)0)-》member ) *__mptr = (ptr); \

(type *)( (char *)__mptr - offsetof(type,member) );})

container_of在     Linux   Kernel中的应用非常广泛,它用于通过结构体某个成员变量的地址获得整个结构体的入口地址。

首先解释下宏定义中出现的另外两个关键字或者宏定义。

typeof:获得变量类型。

如:

char* pc;

typeof(*pc) c;

c = ‘a’;

这个例子中,typeof(*pc)就相当于char,所以变量c的类型就是char型变量。

offsetof(type,member):member变量在type结构体中的偏移量。

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)-》MEMBER)

TYPE是某struct的类型,0是一个假想TYPE类型struct,MEMBER是该struct中的一个成员。 由于该struct的基地址为0, MEMBER的地址就是该成员相对与struct头地址的偏移量。

下面介绍container_of的具体实现:container_of(ptr, type, member):

const typeof( ((type *)0)-》member ) *__mptr = (ptr);

意思是声明一个与member同一个类型的指针常量 *__mptr,并初始化为ptr,注意typeof( ((type *)0)-》member )就是获得member变量的类型。前面加上const,是为了保证后面的0不被改动。

(type *)( (char *)__mptr - offsetof(type,member) );意思是__mptr的地址减去member在该struct中的偏移量得到的地址, 再转换成type型指针。 该指针就是member所在结构体的入口地址了。为什么要先强制转换为char类型指针呢? 如果_mptr为整形指针 _mptr - offset 相当于减去 sizeof(int)*offset个字节。

Linux内核基础_container_of_设计制作_接口/总线/驱动
81
29
0
78

相关资讯

  1. 1、Win10电脑怎么快速取消电脑开机密码?4485
  2. 2、百度网盘怎么修改头像?百度网盘电脑版头像修改方法简述2227
  3. 3、打印机出现win10依赖服务1068错误无法正常打印怎么办2488
  4. 4、小黑屋如何导出文档?小黑屋导出文档的方法3867
  5. 5、EV视频转换器怎么合并视频?EV视频转换器合并不同格式视频的方法3628
  6. 6、Win10电脑怎么连接打印机?Win10连接打印机方法教程519
  7. 7、宝驾公车如何添加提现账户?宝驾公车添加提现账户的方法2495
  8. 8、Win10怎么安装回原来的IE浏览器?796
  9. 9、360游戏大厅怎么更换皮肤?360游戏大厅皮肤更换方法简述2464
  10. 10、PS自动关闭怎么解决?自动关闭解决方法2001
全部评论(0)
我也有话说
0
收藏
点赞
顶部