【问题标题】:The Linux Kernel container_of macro and generic containers in C90C90 中的 Linux Kernel container_of 宏和通用容器
【发布时间】:2011-04-08 11:43:57
【问题描述】:

是否可以在纯 C90 中实现 container_of 宏?我不确定该怎么做,因为内核实现依赖于GCC Hacks,例如typeof 运算符。

我问是因为我想在 C90 中实现一个类似于内核的linked list 的通用容器。我正在考虑的实际容器是一个序列集,类似于您可能从Boost MultiIndex 获得的。

【问题讨论】:

    标签: c data-structures linux-kernel typeof c89


    【解决方案1】:

    container_of() 的内核定义中使用typeof 仅用于编译时类型检查——它确保传递的ptr 确实是指向与member 相同类型的指针。可以以这种类型检查为代价将其修改为完全 ANSI C:

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

    (offsetof()<stddef.h>)

    【讨论】:

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