问题描述
user/include/linux/list.h
这声明:
#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。请简化您的回答尽可能,我知道线程,在Linux进程,现在我探索的可能性,我坚持这一个一点点。
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.
推荐答案
考虑两个结构是这样的:
Consider two structs like this:
struct data {
int something;
};
struct container {
int something_before;
struct data data_item;
int something_after;
};
假设你有一个指针结构数据
值:
struct data *data_ptr;
的 LIST_ENTRY()
宏可以帮助你 DATA_PTR
转换为指针结构容器
值保存在结构数据
值, PTR
指出:
The list_entry()
macro helps you to convert data_ptr
to a pointer to the struct container
value that holds the struct data
value, pointed to by ptr
:
struct container *cont_ptr = list_entry(data_ptr, struct container, data_item);
宏的作品通过计算偏移 data_item
的结构容器
里面,减去从多少字节 DATA_PTR
指针。对此,转换为结构容器*
时,给出了一个有效的指针到结构容器
保存这个特殊的结构数据
内部。
The macro works by computing the offset of data_item
inside the struct container
, and subtracting that many bytes from the data_ptr
pointer. This, when cast to struct container *
, gives a valid pointer to the struct container
that holds this particular struct data
"inside".
宏也可以通过使用内置简化了一下 offsetof()
宏:
The macro can also be simplified a bit by using the builtin offsetof()
macro:
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr) – offsetof(type, member)))
这篇关于LIST_ENTRY在Linux中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!