您的位置:首页 > 其它

list_entry

2013-08-14 15:54 211 查看
list.h中源码如下:

/**
* 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源码在kernel.h中有定义:
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

#ifndef container_of
/**
* 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)); })
#endif


对链表的使用一般如下所示:

struct my_struct {
char num;
//......
struct list_head list;
};


list_entry是已知了某个节点上list_head的指针,获取该节点的指针。之前总是看着三个入参不知所措,揪出来看看比较好。

* @ptr:	该结构体节点中list_head的指针
* @type:	该指针所在的结构体
* @member:	@ptr这个指针在@type这个结构体中的名称


对于my_struct这个结构体:|--num--|--list--|,即已知了list的位置,求这个结构体起始位置,用list指针位置减掉该变量相对结构体的偏移即可。而container_of宏就是这个作用,这个宏的解释百度一下就好,不过很多解释都没提到为什么需要__mptr常量,原因是让编译器做类型检查
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: