linux中非常有趣的函数container_of实验

今天看linux代码,看到container_of函数,可以从结构体的成员指针,加上结构体类型,得到指向结构体头的指针,非常有趣。


这一段是container_of的宏定义


/Users/foursking/Documents/linux/linux-2.6.24/include/linux/kernel.h:
  350  
  351  /**
  352:  * container_of - cast a member of a structure out to the containing structure
  353   * @ptr:	the pointer to the member.
  354   * @type:	the type of the container struct this is embedded in.
  ...
  356   *
  357   */
  358: #define container_of(ptr, type, member) ({			\
  359  	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
  360  	(type *)( (char *)__mptr - offsetof(type,member) );})


看这段函数不大明白,于是我做了如下的实验,代码如下


#include <stdio.h>

struct list_head{
	struct list_head *next,*prev;
};

struct test{
	int a;
	int b;
	struct list_head *f_list;
	int c;
};
//this code indicate the engine of container_of
int main(void)
{
	
	struct list_head* ptr;
	struct test* test1;
	 
	
	long offset=(long)&((struct test*)0)->f_list;
	printf("offset: %ld\n",offset);
	//we caculate the ptr offset in struct test
	
	const struct test* __mptr=ptr;
	(struct test*)((char *)__mptr-offset);
	return 0;
	//first, we point __mptr to ptr
	//next, we minus offset in __mptr so we point to the first element 
	//of struct test
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
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 ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值