linux/list.h 中container_of 宏背后的基本原理

发布于 2024-11-09 10:07:02 字数 1081 浏览 0 评论 0原文

/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)

In the implementation of linux kernel lists in /include/linux/list.h, what is the rationale behind the first line (pasted below) of the container_of macro?

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

In a sample code of mine, I removed this line and changed the definition to

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

and my code still showed expected results. Is the first line redundant then? Or does it have some hidden trap that I am not aware of?

The code I found at 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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏末的微笑 2024-11-16 10:07:02

它添加了一些类型检查。对于您的版本,编译良好(没有警告):

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。

It adds some type checking. With your version, this compiles fine (without warning):

struct foo { int bar; };

....

float a;
struct foo *var = container_of(&a, foo, bar);

With the kernel version, the compiler reports:

warning: initialization from incompatible pointer type

Good explanation of how the macro works: container_of by Greg Kroah-Hartman.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文