这个函数可以通过list的指针域推算出它的节点所指向的值,具体代码实现如下:
/**
* 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) \
container_of(ptr, type, member)
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#undef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
链表的结构可以表示成如下的形式:
p--------------------------> | |
---|---|
pos------------------------> | next |
prev |
关键就是看如何通过pos的地址算出p的地址,p指向链表的开头。在这里让p的地址为0,那么它里面的成员member的地址就是偏移的大小,member就是list_head在成员中的名字。
ptr是list_head的地址,减去这个偏移就是节点的地址,取这个地址的内容就可以得到节点的值。