本文介绍了LIST_ENTRY在Linux中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 12:15