linux / list.h中container_of宏背后的原理

时间:2011-05-21 18:45:29

标签: c pointers struct linux-kernel linked-list

/include/linux/list.h中的linux内核列表的实现中,container_of宏的第一行(下面粘贴)背后的基本原理是什么?

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

在我的示例代码中,我删除了这一行并将定义更改为

#define container_of(ptr, type, member) ({                      \
     (type *)( (char *)ptr - offsetof(type,member) );})

我的代码仍然显示了预期的结果。那么第一行是多余的吗?或者它有一些我不知道的隐藏陷阱?

我在Faq/LinkedLists

找到的代码
/**
 * 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)

1 个答案:

答案 0 :(得分:34)

它添加了一些类型检查。使用您的版本,这可以很好地编译(没有警告):

struct foo { int bar; };

....

float a;
struct foo *var = container_of(&a, foo, bar);

使用内核版本,编译器会报告:

warning: initialization from incompatible pointer type

宏观如何运作的好解释:Greg Kroah-Hartman的container_of