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