您的位置 首页 软件

Linux内核根底-container_of

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

/**

* container_of – cast a member of a structure out to the containing structure

* @ptr: the pointer 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个字节。

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/qianrushi/ruanjian/90115.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部