container_of()

kernel version "2.6.35.7-perf"
include/linux/
/**

 * container_of - cast a member of a structure out to the containing structure
 * @ptr:    the pointer to the member.                                                   //struct中的member类型的指针
 * @type:    the type of the container struct this is embedded in.    //包含ptr的struct
 * @member:    the name of the member within the struct.             //struct中需要对应的类型名
 *
 */
#define container_of(ptr, type, member) ({            \
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \

    (type *)( (char *)__mptr - offsetof(type,member) );})

1. ( (type *)0 ) 将零转型为type 类型指针; 2. ((type *)0)->member 访问结构中的数据成员; 3. &( ( (type *)0 )->member )取出数据成员的地址; //typeof( ((type *)0)->member ) *__mptr = (ptr); 获得了结构中member成员的地址 4. offsetof = (size_t)(&(((type *)0)->member ))结果转换类型。巧妙之处在于将0转换成(TYPE*),结构以内存空间首地址0作为起始地址,则成员地址自然为偏移地址; 5. __mptr - offset获得结构的起始地址; 
由member数据成员ptr指针获得整个struct的指针。

你可能感兴趣的:(container_of())