in linux/include/linux/list.h https://github.com/torvalds/linux/blob/305230142ae0637213bf6e04f6d9f10bbcb74af8/include/linux/list.h#L600我发现:
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_head within the struct.
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
“获取此条目的结构”是什么意思我可以查看使用示例以更好地理解吗?
这是 C 语言中多态性的一个很好的例子。借用 C++ 的术语,list_entry()
宏允许你从list_head
类型为包含它的任何类型。
看一下kthread.c
一个简单的基本示例:
内核/kthread.c:
struct kthread_create_info
{
/* Information passed to kthread() from kthreadd. */
int (*threadfn)(void *data);
void *data;
int node;
/* Result passed back to kthread_create() from kthreadd. */
struct task_struct *result;
struct completion *done;
struct list_head list;
};
...
int kthreadd(void *unused)
{
...
while (!list_empty(&kthread_create_list)) {
struct kthread_create_info *create;
create = list_entry(kthread_create_list.next,
struct kthread_create_info, list);
...
create_kthread(create);
通过包括list_head
对象在kthread_create_info
结构体,你可以这样说kthread_create_info
“源自于list_head
。这允许kthread_create_info
用作列表中的节点的对象,这意味着您可以将它们传递给中声明的任何函数list.h
通过简单地取消引用list
结构体的成员。这list_entry
然后,宏为您提供从基类指针到其派生起始地址的映射。
换句话说,给定一个list_head
您知道的对象包含在外部kthread_create_info
struct,您可以恢复指向kthread_create_info
容器。
这是 C 编程中极其常见的模式,其中需要面向对象的构造,但 C++ 编译器不可用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)