gpt4 book ai didi

c - 内核的 "container_of"- 有什么方法可以使其符合 ISO 标准吗?

转载 作者:行者123 更新时间:2023-11-30 16:31:26 24 4
gpt4 key购买 nike

在查看 Linux 内核的双向链接循环列表实现时,我发现了以下宏:

#define container_of(ptr, type, member) ({           \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})

其工作方式是,它返回指向结构的指针,仅给出其成员之一的地址:

struct blabla
{
int value;
struct list_head *list;
}

因此,仅给出指向列表的指针,您就可以获得指向 blabla 的指针(并获得“值”)。对于我的问题,我如何使其尽可能便携(最好的情况符合 C89/C99?)。由于使用了 typeof(),这仅适用于 gcc。

这是我到目前为止所得到的:

#define container_of(ptr, type, member) (                  \
(type *) (char *)(ptr)-offsetof(type,member)\
)

此代码片段是否符合 ISO 标准(因此应该能够在任何符合标准的编译器上进行编译)?

最佳答案

正如 Ouah 所评论的,({ ... }) 语句表达式是一个 GNU 扩展;你将无法使用它。您的核心表达式接近所需的内容,但没有足够的括号:

#define container_of(ptr, type, member) \
((type *) ((char *)(ptr) - offsetof(type, member)))

对我来说这看起来很干净。 SO 只分布在两条线上。

关于c - 内核的 "container_of"- 有什么方法可以使其符合 ISO 标准吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50608303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com