通过结构体的成员获得结构体的地址,摘自kernel的一段宏,为了理解container_of,写了个例子
#include <stdio.h> #include <stdlib.h> #include <string.h> #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) );}) struct example{ unsigned char ea; int eb; int ec; }; int main() { struct example *example=malloc(sizeof(struct example)); memset(example,0,sizeof(struct example)); printf("%p\n",example); printf("%p\n",&(example->ec)); printf("%p\n",(void *)offsetof(struct example,ec)); printf("%p\n",container_of(&(example->ec),struct example,ec)); free(example); example=NULL; return 0; } |
---|