Linux 中的 list_entry [英] list_entry in Linux
问题描述
user/include/linux/list.h
本声明:
#define list_entry(ptr, type, member) ((type *)((char *)(ptr) – (unsigned long)(&((type *)0)->member)))
谁能解释一下这是什么以及它是如何工作的,在此先感谢
附言请尽可能简化您的答案,我了解 Linux 中的线程和进程,现在我正在探索各种可能性,但我对这个问题有点困惑.
考虑两个这样的结构:
结构数据{输入一些东西;};结构容器{int something_before;结构数据data_item;int something_after;};
假设您有一个指向 struct data
值的指针:
struct data *data_ptr;
list_entry()
宏可帮助您将 data_ptr
转换为指向保存 struct 数据的
值,由 struct 容器
值的指针ptr
指向:
struct container *cont_ptr = list_entry(data_ptr, struct container, data_item);
宏的工作原理是计算 struct 容器
中 data_item
的偏移量,然后从 data_ptr
指针中减去那么多字节.当转换为 struct container *
时,它会给出一个指向 struct container
的有效指针,该指针包含这个特定的 struct data
inside".>
宏也可以通过使用内置的 offsetof()
宏来简化:
#define list_entry(ptr, type, member) ((type *)((char *)(ptr) – offsetof(type, member)))
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.
Consider two structs like this:
struct data {
int something;
};
struct container {
int something_before;
struct data data_item;
int something_after;
};
Assume you have a pointer to a struct data
value:
struct data *data_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);
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".
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)))
这篇关于Linux 中的 list_entry的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!