【问题标题】:Rationale behind the container_of macro in linux/list.hlinux/list.h 中的 container_of 宏背后的基本原理
【发布时间】:2011-08-30 08:04:11
【问题描述】:

/include/linux/list.h 中实现linux 内核列表时,container_of 宏的第一行(粘贴在下面)背后的基本原理是什么?

const typeof( ((type *)0)->member ) *__mptr = (ptr);

在我的示例代码中,我删除了这一行并将定义更改为

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

我的代码仍然显示了预期的结果。那么第一行是多余的吗?还是它有一些我不知道的隐藏陷阱?

我在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)

【问题讨论】:

    标签: c pointers struct linux-kernel linked-list


    【解决方案1】:

    它增加了一些类型检查。使用你的版本,这编译得很好(没有警告):

    struct foo { int bar; };
    
    ....
    
    float a;
    struct foo *var = container_of(&a, foo, bar);
    

    使用内核版本,编译器报告:

    warning: initialization from incompatible pointer type
    

    很好地解释了宏的工作原理:container_of,Greg Kroah-Hartman。

    【讨论】:

      猜你喜欢
      • 2013-03-27
      • 2011-03-11
      • 1970-01-01
      • 2014-12-19
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 2013-02-12
      相关资源
      最近更新 更多