内核的"container_of" -是否可以使其符合ISO标准? [英] Kernel's "container_of" - any way to make it ISO conforming?

查看:88
本文介绍了内核的"container_of" -是否可以使其符合ISO标准?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看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的指针(并指向"value"). 对于我的问题,我将如何使其尽可能便携(最佳情况是符合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.

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

This is what I've got so far:

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆