Linux 中的列表条目
user/include/linux/list.h
此声明:
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr) – (unsigned long)(&((type *)0)->member)))
有人可以解释一下这是什么以及它是如何工作的,提前
致谢请尽可能简化你的答案,我了解Linux中的线程、进程,现在我正在探索可能性,但我对这个问题有点困惑。
user/include/linux/list.h
this declaration:
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr) – (unsigned long)(&((type *)0)->member)))
can somebody please explain what is this and how does it work, thanks in advance
P.S. please simplify your answer as much as possible, I know about threads, processes in Linux, now I'm exploring possibilities and I'm a little bit stuck with this one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑这样的两个结构:
假设您有一个指向
struct data
值的指针:list_entry()
宏可帮助您将data_ptr
转换为指向保存struct data
值的struct 容器
值的指针,由ptr
指向:该宏通过计算
的偏移量来工作data_item
在struct 容器
中,并从data_ptr
指针中减去那么多字节。当转换为struct container *
时,会给出一个指向“内部”保存此特定struct数据
的struct container
的有效指针。还可以使用内置的
offsetof()
宏来稍微简化该宏:Consider two structs like this:
Assume you have a pointer to a
struct data
value:The
list_entry()
macro helps you to convertdata_ptr
to a pointer to thestruct container
value that holds thestruct data
value, pointed to byptr
:The macro works by computing the offset of
data_item
inside thestruct container
, and subtracting that many bytes from thedata_ptr
pointer. This, when cast tostruct container *
, gives a valid pointer to thestruct container
that holds this particularstruct data
"inside".The macro can also be simplified a bit by using the builtin
offsetof()
macro:您可以在此处找到对此的解释:部分这是如何工作的?
An explanation of this you find here: Section How Does This Work?
该宏用于查找给定其成员之一的结构的地址。
因此,例如,假设您有结构:
您需要知道的第一件事是宏的最后部分:
用于给出成员的偏移量。因此,它是从零内存转换为类型和成员的大小(以字节为单位)。在本例中,它是
sizeof(int)
,因为j
就在int i
下面;因此,为了简单起见,我们假设该表达式值为4
。使用宏可以得到相同的结果现在我们要计算
temp
的地址,其中temp
是typestruct temp
。为此,我们简单地计算指针的地址减去成员位置。指针的地址是:因此,减法是:
或者,就像宏所说:
你可以了解更多 此处,以及此问题。
(括号是必要的,但为了澄清而被删除)
This macro is used to find the address of a struct given one of its member.
So, for example, suppose you have the struct:
First thing you need to know is that the last part of the macro:
Is used to give the offset of a member. So, it is the size, in bytes, from the zero memory casted to the type, to the member. In this case, it is the
sizeof(int)
, becausej
is just bellowint i
; So lets assume this expression values4
for simplicity. You can get the same result with the macroNow we want to calculate the address of
temp
, wheretemp
istypestruct temp
. To do that, we simple compute the address of the pointer minus the member position. The address of the pointer is:Hence, the subtraction is:
or, like the macro says:
You can learn much more here, and also in this question.
(Parenthesis are necessary, but was eliminated for clarification)