【转】Linux内核的container_of宏

Linux内核的container_of宏

作用:

通过一个结构的成员的地址和结构名以及成员名,获得结构的首地址。

 

宏定义:

include/linux/kernel.h

C代码 复制代码
  1. /**  
  2.  * container_of - cast a member of a structure out to the containing structure  
  3.  * @ptr:    the pointer to the member.  
  4.  * @type:   the type of the container struct this is embedded in.  
  5.  * @member: the name of the member within the struct.  
  6.  *  
  7.  */  
  8. #define container_of(ptr, type, member) ({          /   
  9.     const typeof( ((type *)0)->member ) *__mptr = (ptr); /   
  10.     (type *)( (char *)__mptr - offsetof(type,member) );})  

思路很简单:

ptr-(member在type内的偏移地址)

求member在type内的偏移地址有个小技巧,将地址0转换成一个member对象,然后这个对象的成员member的地址就是偏移量。

 

在宏的定义用用了一个C99的标准宏offsetof,它的作用是取得一个结构体中成员的偏移量。

一个比较常见的宏实现如下:

C代码 复制代码
  1. /**  
  2.  * offset_of - get the offset of a member to its struct  
  3.  * @type:   the name of the struct  
  4.  * @member: the name of the member  
  5.  */  
  6. #define offset_of(type,member) ({ /   
  7.     (size_t)&(((type*)0)->member);})  

 

在这个宏的最后一句,不能将__mptr转换成void*,因为void*指针不能参与算术运算。

 

这里是直接用typeof来定义类型。

比如这样:

C代码 复制代码
  1. const typeof(a) b;  

 这是一个定义,将b定义成和a一样的类型,且是const的。

Linux内核中,container_of是一个定义,用于获取包含某个成员的结构体变量的地址。它的定义可以在include/linux/kernel.h中找到。该的作用是通过给定的成员指针,返回包含该成员的结构体变量的地址。具体的定义如下: ```c #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) ``` 这个的使用非常方便,可以通过成员指针来获取整个结构体变量的地址。在进行内核驱动开发时,经常会用到这个来获取结构体变量的地址,以便进行相关操作。 #### 引用[.reference_title] - *1* [Linux内核:理解container_of](https://blog.csdn.net/qq_28877125/article/details/124209504)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Linux内核container_of的原理及其使用详解](https://blog.csdn.net/u010632165/article/details/107523477)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值