# 一、定义 Linux内核代码有以下两个define,经常被使用: ```cpp #define offsetof(type, member) (size_t)&(((type*)0)->member) #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) ``` # 二、作用 - offsetof:计算成员在结构体中的偏移。 - container\_of:根据结构体成员的地址获得,该成员所在结构体实例地址。 # 三、示例 ```cpp struct SA { int alpha; int beta; } struct SA *my_sa = (struct SA *)malloc(sizeof(struct SA)); int *beta_ptr = &my_sa->beta; // beta的地址是beta_ptr,则通过beta_ptr可以获得my_sa地址。 struct SA *my_sa_check = container_of(beta_ptr, struct SA, beta); assert(my_sa_check == my_sa); ``` # 四、参考 - [Understanding container_of macro in the Linux kernel](https://stackoverflow.com/questions/15832301/understanding-container-of-macro-in-the-linux-kernel) - [offsetof与container_of宏](https://www.cnblogs.com/Anker/p/3472271.html) - [C语言中的typeof关键字](https://www.jianshu.com/p/9dc0494dd5c4)