(type*)0->member什么含义

内核源码中形如:(type*)0->member 是什么含义??

type:结构体类型
member:结构体的成员

作者: shaohui973   发布时间: 2011-02-15

百度一下contain_of 网上有很多

作者: amarant   发布时间: 2011-02-15

复制点东西过来给lz参考,
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
先分析一下这个 宏的运行机理:
一共4步
1. ( (TYPE *)0 ) 将零转型为TYPE类型指针;
2. ((TYPE *)0)->MEMBER 访问结构中的数据成员;
3. &( ( (TYPE *)0 )->MEMBER )取出数据成员的地址;
4.(size_t)(&(((TYPE*)0)->MEMBER))结果转换类型。巧妙之处在于将0转 换成(TYPE*),结构以内存空间首地址0作为起始地址,则成员地址自然为偏移地址;

作者: amarant   发布时间: 2011-02-15



QUOTE:
3. &( ( (TYPE *)0 )->MEMBER )取出数据成员的地址;


补充一下:
这个实现相当于获取到了 MEMBER 成员相对于其所在结构体的偏移,也就是其在对应结构体中的什么位置。

作者: Godbach:   发布时间: 2011-02-15

以前没弄懂

作者: Godbach   发布时间: 2011-02-15

那这里的0地址 (type*)0和全局描述符表的第一项用来表示0地址有什么关系?是同一个吗?如果是的话,那么要是对 (type*)0->member赋值应该会报错吧?

作者: ww2000e   发布时间: 2011-02-15

这个内核中用的较多,可以看一下 container_of 的实现
  1. /**
  2. * container_of - cast a member of a structure out to the containing structure
  3. * @ptr:        the pointer to the member.
  4. * @type:        the type of the container struct this is embedded in.
  5. * @member:        the name of the member within the struct.
  6. *
  7. */
  8. #define container_of(ptr, type, member) ({                        \
  9.         const typeof( ((type *)0)->member ) *__mptr = (ptr);        \
  10.         (type *)( (char *)__mptr - offsetof(type,member) );})
复制代码

作者: shaohui973   发布时间: 2011-02-15

本帖最后由 Godbach 于 2011-02-15 11:57 编辑


QUOTE:
那这里的0地址 (type*)0和全局描述符表的第一项用来表示0地址有什么关系?是同一个吗?如果是的话,那么要是对 (type*)0->member赋值应该会报错吧


这里用作读取,计算出 member 成员相对于所在结构体起始位置的偏移,不会执行写入动作的。

作者: Godbach   发布时间: 2011-02-15