C语言宏 offsetof 和 containerof 的解析

offsetof: 返回结构成员在结构体中的地址偏移量。
    Retrieves the offset of a member from the beginning of its parent structure.

size_t offsetof(structName, memberName);

Parameters:
    structName : Name of the parent data structure.
    memberName :Name of the member in the parent data structure for which to determine the offset.

Return Value : offsetof returns the offset in bytes of the specified member from 
          the beginning of its parent data structure. It is undefined for bit fields.
Remarks :
    The offsetof macro returns the offset in bytes of memberName from the beginning of the structure specified by structName. You can specify types with the struct keyword.

Note  :
    offsetof is not a function and cannot be described using a C prototype.

 

 #define offsetof(s, m)   (size_t)&(((s *)0)->m)

#define offsetof(s, m) (size_t)&(((s *)0)->m)

s是一个结构名,它有一个名为m的成员(s和m 是宏offsetof的形参,它实际是返回结构s的成员m的偏移地址.

(s *)0 是骗编译器说有一个指向类(或结构)s的指针,其地址值0 

&((s *)0)->m   是要取得类s中成员变量m的地址. 因基址为0,这时m的地址当然就是m在s中的偏移

最后转换size_t 型,即unsigned int。

 

containerof:

链表是内核最经典的数据结构之一,说到链表就不得不提及内核最经典(没有之一)的宏container_of。

container_of似乎就是为链表而生的,它的主要作用是根据一个结构体变量中的一个域成员变量的指针来获取指向整个结构体变量的指针,最典型的应用就是根据链表节点获取链表上的元素对象。

container_of的宏定义如下:

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

这个宏乍一看有点瘆人,宏里面包含了两个关键字:typeof和offsetof:typeof是GNU对C新增的一个扩展关键字,用于获取一个对象的类型,在很多时候我们处理的对象通常是一个指针,而此时如果想知道指针所指向的对象的类型,typeof就派上用场了,详见GNU的官方文档:http://gcc.gnu.org/onlinedocs/gcc/Typeof.html 

 

现在看container_of宏的第一条语句:

  1. const typeof( ((type *)0)->member ) *__mptr = (ptr); \

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

  1. (type *)( (char *)__mptr - offsetof(type,member) );}

另一个主角出场了---offsetof,返回一个数据域在它所属的数据结构中的相对偏移,单位是size_t,宏定义如下:

  1. #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的实现其实也是蛮清晰的,记得某位兄台说过一句话:一切事物在你看清楚它的本质之前,对你而言总是朦胧的。

转载于:https://my.oschina.net/xolsenberg/blog/743536

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值