list_entry()

来源:互联网 发布:360浏览器使用js脚本 编辑:程序博客网 时间:2024/05/22 11:58
list_entry,计算机语言,原理是指针ptr向结构体type成员member。

定义

编辑
/* 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_struct within the struct.*/
#define list_entry(ptr, type, member) ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

描述

编辑
我们使用list_entry()宏在linux链表中访问链表数据。
原理为指针ptr指向结构体type中的成员member;通过指针ptr,返回结构体type的起始地址。
定义中((unsigned long) &((type *)0)->member)意为:把0地址转化为type结构的指针,然后获取该结构中member成员的指针,并将其强制转换为unsigned long类型

例子


如果我们有test_list结构:
struct test_list{
int testdata;
struct list_head list;};
struct test_list a;
a.testdata = 5;
struct test_list *pos = list_entry(&(a.testdata),struct test_list,testdata);
结果:
pos = &a;
可测试:
pos->testdata = 5

解释

编辑
&((type *)0)->member:
把0强制转化为指针类型,即0是一个地址,为段基址。取以0为结构体基址的结构体的域变量member的地址,那么这个地址就等于member域到结构体基地址的偏移字节数。
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))):
ptr是指向类型为type的某结构体中的成员member的指针,减去该member在结构体中的偏移量,即得到该结构体的起始地址。
0 0