【发布时间】:2011-08-30 08:04:11
【问题描述】:
在/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)
【问题讨论】:
标签: c pointers struct linux-kernel linked-list