在linux / list.h的container_of宏观背后的理由 [英] Rationale behind the container_of macro in linux/list.h
问题描述
在linux内核列表中 /include/linux/list.h
的实施,什么是第一线背后的基本原理(粘贴以下)的<$ C的$ C> container_of 宏?
常量的typeof(((键入*)0) - &GT;成员)* __ mptr =(PTR);
在我的一个样本code,我删除了这条线,改变了定义
的#define container_of(PTR,类型,成员)({\\
(类型*)((字符*)PTR - offsetof(类型,成员));})
和我的code仍表现出预期的效果。第一行是多余的呢?还是有一些隐藏的陷阱,我不知道的?
在code,我发现在常见问题/ LinkedLists
/ **
* container_of - 蒙上了结构的成员到包含结构
* @ptr:指针成员。
* @type:容器结构这被嵌入的类型。
* @member:结构中的成员的名称。
*
* /
#定义container_of(PTR,类型,成员)({\\
常量的typeof(((键入*)0) - &GT;成员)* __ mptr =(PTR); \\
(类型*)((字符*)__ mptr - offsetof(类型,成员));})的#define offsetof(TYPE,MEMBER)((为size_t)及((TYPE *)0) - &GT; MEMBER)
它增加了一些类型检查。有了您的版本,这个编译好(无警告):
结构foo的{INT吧; };....浮动;
结构美孚* VAR = container_of(安培A,富,酒吧);
通过内核版本,编译器会报告:
警告:初始化从兼容的指针类型
如何在宏的作品很好的解释: container_of 通过葛雷格·克罗哈曼
In the implementation of linux kernel lists in /include/linux/list.h
, what is the rationale behind the first line (pasted below) of the container_of
macro?
const typeof( ((type *)0)->member ) *__mptr = (ptr);
In a sample code of mine, I removed this line and changed the definition to
#define container_of(ptr, type, member) ({ \
(type *)( (char *)ptr - offsetof(type,member) );})
and my code still showed expected results. Is the first line redundant then? Or does it have some hidden trap that I am not aware of?
The code I found at 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)
It adds some type checking. With your version, this compiles fine (without warning):
struct foo { int bar; };
....
float a;
struct foo *var = container_of(&a, foo, bar);
With the kernel version, the compiler reports:
warning: initialization from incompatible pointer type
Good explanation of how the macro works: container_of by Greg Kroah-Hartman.
这篇关于在linux / list.h的container_of宏观背后的理由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!