内核的“container_of"- 有什么办法让它符合 ISO 标准吗? [英] Kernel's "container_of" - any way to make it ISO conforming?
问题描述
在查看 Linux 内核对双向循环列表的实现时,我发现了以下宏:
While looking at Linux kernel's implementation of doubly linked circular lists, I've found following macro:
#define container_of(ptr, type, member) ({
const typeof( ((type *)0)->member ) *__mptr = (ptr);
(type *)( (char *)__mptr - offsetof(type,member) );})
它的工作方式是仅在给定其成员之一的地址的情况下返回指向结构的指针:
The way this works is that it returns pointer to structure given only address of one of its members:
struct blabla
{
int value;
struct list_head *list;
}
因此,只要给出指向列表的指针,您就可以获得指向 blabla 的指针(并获得值").对于我的问题,我将如何使其尽可能便携(符合 C89/C99 的最佳情况?).由于使用了 typeof(),这只是 gcc.
Thus you can get pointer to blabla (and get to "value") given only pointer to list. To my question, how would I make this as portable as possible (best case conforming to C89/C99?). Due to usage of typeof(), this is gcc only.
这是我目前得到的:
#define container_of(ptr, type, member) (
(type *) (char *)(ptr)-offsetof(type,member)
)
这个片段是否符合 ISO 标准(因此应该能够在任何符合标准的编译器上编译)?
Is this snippet conforming to ISO standards (and thus should be able to be compiled on any conforming compiler)?
推荐答案
正如 Ouah 所评论的,({ ... })
语句表达式是一个 GNU 扩展;你将无法使用它.您的核心表达式接近所需内容,但没有足够的括号:
As Ouah commented, the ({ ... })
statement expression is a GNU extension; you won't be able to use that. Your core expression is close to what's required, but doesn't have enough parentheses:
#define container_of(ptr, type, member)
((type *) ((char *)(ptr) - offsetof(type, member)))
这对我来说看起来很干净.对于 SO,它仅分布在两行中.
That looks clean to me. It's only spread across two lines for SO.
这篇关于内核的“container_of"- 有什么办法让它符合 ISO 标准吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!