在linux内核列表中的实现/include/linux/list.h
,第一行(粘贴在下面)背后的基本原理是什么container_of
macro?
const typeof( ((type *)0)->member ) *__mptr = (ptr);
在我的示例代码中,我删除了这一行并将定义更改为
#define container_of(ptr, type, member) ({ \
(type *)( (char *)ptr - offsetof(type,member) );})
我的代码仍然显示了预期的结果。那么第一行是多余的吗?还是其中隐藏着一些我不知道的陷阱?
我在以下位置找到的代码常见问题解答/链接列表 http://kernelnewbies.org/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)
它添加了一些类型检查。使用您的版本,可以正常编译(没有警告):
struct foo { int bar; };
....
float a;
struct foo *var = container_of(&a, foo, bar);
对于内核版本,编译器报告:
warning: initialization from incompatible pointer type
很好地解释了宏的工作原理:容器的 http://www.kroah.com/log/linux/container_of.html作者:格雷格·克罗-哈特曼。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)