内核之container_of的理解

最近在公司用户态看到有些地方使用了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 - ((size_t) &((type *)0)->member) );})
简单的理解一下这个container_of宏函数:

第一句:首先定义了一个__mptr的指针,这个指针的类型是typeof( ((type *)0)->member ),这个指针里存放的数据是ptr的值,ptr是什么呢,ptr是type结构体中member成员的地址指针。

第二句:(size_t) &((type *)0)->member这个的意思是将0地址强转为type *类型,然后对member成员取地址,那么现在我们可以想到,对于一个以0地址为头指针的结构体,member成员的地址即为头指针和member间的相对偏移。最后用__mptr减去这个相对偏移即可以得到结构体type的头指针。 

现在一起探讨一个问题,为什么要定义一个__mptr来存储ptr的值,我们完全可以用下面的宏:

#define container_of(ptr, type, member)({\

   (type *)((char *)(ptr) - ((size_t)&((type *)0->member)));})

效果也是一样的嘛,希望知道原因的高手不吝赐教。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值