在Linux内核源码中,实现和链表相关的接口list_entry()
时,会调用container_of()
宏定义,它的作用是:给定结构体中某个成员的地址、该结构体类型和该成员的名字获取这个成员所在的结构体变量的首地址。有点绕,没关系,接着往下看就能明白了。
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) );})
要看懂上述代码,需要知道三个关键点:
- typeof(),取变量或表达式类型,可参考