container_of的理解

container_of(pointer, container_type, container_field)

pointer: 指向被包含的container_field的地址

container_type: 包含container_field的结构的类型

container_field: container_type中的一个成员名称

 

该宏通过一个指向container_type 结构内container_field的指针地址,返回这个container_type结构的地址

宏实现

/**
* 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) );})

 

typeof( ((type *)0)->member)

获取结构中member成员的类型

 

关于offsetof

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

返回成员MEMBER在TYPE中的偏移量
 

你可能感兴趣的:(struct,structure)