定义
/* 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 *))->member)))
描述
我们使用list_entry()宏在linux链表中访问链表数据。
原理为指针ptr指向结构体type中的成员member;通过指针ptr,返回结构体type的起始地址。
定义中((unsigned long) &((type *))->member)意为:把地址转化为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 *))->member:
把强制转化为指针类型,即是一个地址,为段基址。取以为结构体基址的结构体的域变量member的地址,那么这个地址就等于member域到结构体基地址的偏移字节数。
((type *)((char *)(ptr)-(unsigned long)(&((type *))->member))):
ptr是指向类型为type的某结构体中的成员member的指针,减去该member在结构体中的偏移量,即得到该结构体的起始地址。