问题描述
container_of( )
在Linux内核中宏定义为:
的#define container_of(PTR,类型,成员)({\\
常量的typeof(((键入*)0) - >成员)* __mptr =(PTR); \\
(类型*)((字符*)__ mptr - offsetof(类型,成员));})
为什么这样使用((类型*)0) - >成员
,而不是(类型*) - GT;成员
?
Simply because (type*)->member
would be invalid syntax, thus typeof
would be impossible. So it uses a NULL
pointer, which it doesn't dereference anyway - it's used just so typeof
can refer to the member.
How this works:
The
typeof
trick is used to declare a pointer of the type of the member. This pointer gets is initialized with the pointer passed by the callerThe offset of that member in the struct is subtracted from the address of the pointer: this yields the address of the containing object
Subtler issue: why not get rid of typeof
and just do ptr - offsetof
. We're casting it to char *
anyway, right ? In that case you could pass anything as ptr
and the compiler won't say a thing. So the whole typeof
things is there for (rudimentary) type checking.
这篇关于为什么这样0((键入*)0) - >成员用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!