container_of是linux内核中使用非常频繁的一个宏,用于从包含在某个结构中的指针获得结构本身的指针,通俗地讲就是通过结构体变量中某个成员的首地址进而获得整个结构体变量的首地址。
#define container_of(ptr, type, member) ({ \
const typeof(((type *)0)->member) * __mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type, member)); })
其中offsetof的定义:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
该宏用于求结构体中一个成员在该结构体中的偏移量。
如:
typedef struct Test_S {
int a;
char *b;
int c;
}Test_S;
则offsetof(Test_S, c)的值为8,即结构体Test_S中成员c相对于结构体首地址的偏移量为8.
例子:
Test_S test;
printf("%x\n",&test);
printf("%x\n", &test.c);
printf("%x\n", container_of(&test.c,Test_S,c));
输出
ffbef940
ffbef948
ffbef940
即&test和container_of(&test.c,Test_S,c)是相同的