linux/list.h 中 container_of 宏背后的基本原理 [英] Rationale behind the container_of macro in linux/list.h

查看:18
本文介绍了linux/list.h 中 container_of 宏背后的基本原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

推荐答案

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

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

对宏如何工作的很好的解释:container_of 作者 Greg Kroah-Hartman.

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

这篇关于linux/list.h 中 container_of 宏背后的基本原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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