kernel 中 container_of 的原理及使用介绍

kernel 中 container_of 的原理及使用介绍

container_of 原理

container_of : 根据一个结构体变量中的一个域成员变量的指针来获取指向整个结构体变量的指针。

原型:

#define container_of(ptr, type, member) ({			\
	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
	(type *)( (char *)__mptr - offsetof(type,member) );})
源码解析

在这里插入图片描述

第一条语句含义:
const typeof( ((type *)0)->member ) *__mptr = (ptr);
创建一个类型为const typeof( ((type *)0)->member ) *,即类型为type结构的member域所对应的对象类型的常指针__mptr,并用ptr初始化之,这样一来,__mptr就指向了某一个type的member域。因为数据结构是顺序存储的,此时如果知道member在type结构中的相对偏移,那么用__mptr减去此偏移便是ptr所属的type的地址

第二条语句含义:
(type *)( (char *)__mptr - offsetof(type,member) );}

其中 offsetof,返回一个数据域在它所属的数据结构中的相对偏移,单位是size_t,宏定义如下:

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

将地址0强制转换为type *,那么0指向某一个type类型的对象,也就是此type对象的地址,那么(TYPE *)0)->MEMBER就是type的member域,现在取址后&((TYPE *)0)->MEMBER就是member域的地址,因为type的地址为0,则member的地址实质上就是它相对于type地址的偏移。这里为什么可以这样实现而不会出错呢?有两点原因,其一,地址0是在编译器编译时已经指定好了的,其二,这里全部都是取址操作,并没内存数据访问,因此不会存在非法访问内存的问题。

使用示例

/*
 container_of : 根据一个结构体变量中的一个域成员变量的指针来获取指向整个结构体变量的指针,这个宏在链表中应用极为广泛
*/

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

#define container_of(ptr, type, member) ({			\
	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
	(type *)( (char *)__mptr - offsetof(type,member) );})


typedef struct struct_test 
{
	char field1;
	int field2;
	float field3;
}struct_test;


int main (void)
{
	struct_test st_test;
	st_test.field1 = 1;
	st_test.field2 = 9;
	st_test.field3 = 3.145;
	printf("st_test ptr %p st_test.field1 ptr %p st_test.field2 ptr %p st_test.field3 ptr %p \n",
									&st_test,&st_test.field1,&st_test.field2,&st_test.field3);
	printf("st_test ptr %p \n",container_of(&st_test.field1, struct_test, field1));
	printf("st_test ptr %p \n",container_of(&st_test.field2, struct_test, field2));
	printf("st_test ptr %p \n",container_of(&st_test.field3, struct_test, field3));
	return 0;
}


编译运行:

st_test ptr 0x7ffea69cf0ac st_test.field1 ptr 0x7ffea69cf0ac st_test.field2 ptr 0x7ffea69cf0b0 st_test.field3 ptr 0x7ffea69cf0b4 
st_test ptr 0x7ffea69cf0ac 
st_test ptr 0x7ffea69cf0ac 
st_test ptr 0x7ffea69cf0ac 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值