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、金晨与邓伦分手后越来越让人看不懂,不在乎走光发视频还露底裤!3672
  2. 2、与吴京在《长津湖》中饰演中国人民志愿军战士易烊千玺:我会全力以赴演好3523
  3. 3、8月观影指南:七夕混战,小四提档斗于正2733
  4. 4、周润发北京乘车被拒,被司机师傅一句话打脸,更让网友颠覆三观!2836
  5. 5、陈学冬晒出新剧杀青照,当网友认不出你的时候,也许转型就成功了2788
  6. 6、台媒传张惠妹加入中国好声音2当导师一集百万2343
  7. 7、《超凡蜘蛛侠2》两日破亿催泪爱情俘获人心4519
  8. 8、等个官宣!网传经典爱情电影《情书》有望在内地重映387
  9. 9、《碟中谍6》7天7亿助阿汤哥加冕“100亿美元帝”2791
  10. 10、《你好,李焕英》,真情背后的叙事技巧55
全部评论(0)
我也有话说
0
收藏
点赞
顶部