linux中的container of

本文详细解析了container_of宏在C语言中的应用,包括其参数含义、使用方法及实例演示,并解答了相关疑问,如0地址的使用和指针变量的运算问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

container of解释

/** 

 * 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) );})  

  

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)  //这个宏不是在kernel.h文件中定义的。 

 

container_of 宏的作用只有一个:根据结构的成员来获取包含这个成员的结构实例指针。宏中的参数为:

ptr:指向成员的指针。

type:需要返回的结构实例类型。

member:成员在结构实例内部的名称,如果为数组,需要指定下标。

举例:

struct test_struct {  

    int num;  

    char ch;  

    float fl;  

};

int main(void)  

{  

    struct test_struct init_test_struct = { 99, 'C', 59.12 };  

  

    char *char_ptr = &init_test_struct.ch;  

  

    struct test_struct *test_struct = container_of(char_ptr, struct test_struct, ch);  

      

    printf(" test_struct->num = %d\n test_struct->ch = %c\n test_struct->fl = %f\n",   

        test_struct->num, test_struct->ch, test_struct->fl);  

      

    return 0;  

}  

例子输出结果

test_struct->num = 99  

test_struct->ch = C  

test_struct->fl = 59.119999


1、关于就是关于0地址的使用,0地址不是不能被访问吗?

typeof( ((type *)0)->member ) *__mptr = (ptr); 

答:

没错,0地址当然不能被访问,这句话的意思是定义了一个跟member数据类型一样的指针变量__mptr,也就是说如果member的数据类型为int,那么typeof( ((type *) NULL)->member ) *__mptr = (ptr); 就等价于int *__mptr = (ptr);,整个typeof( ((type *) NULL)->member ) 语句就是为了获得成员member的数据类型。


2、(type *)( (char *)__mptr - offsetof(type,member) ); 不明白为什么要把__mptr转换成char *再相减?

这是指针变量的运算问题,举个简单的例子:
int a;
char *p = (char *)&a;
int *q = &a;
这时候,p-1和q-1的值是不是相等呢?
肯定不是,如果&a的值为0xbffe67b4,那么p-1为0xbffe67b3,而q-1则为0xbffe67b0。
因此,指针变量加减n实际上是加减n个数据类型(p为char,q为int)的长度。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值