先看宏offset_of,mem是结构体类型type的成员,作用为计算出mem在结构体type中的偏移量
#define offset_of(type, mem) ({ \
(size_t)(&(((type*)0)->mem)); \
})
再看宏container_of,mem是结构体类型type的成员,定义一个类型为type的变量,ptr为该变量mem成员的指针,作用为通过ptr指针,得到该类型为type变量的指针
#define container_of(ptr, type, mem) ({ \
const typeof(((type*)0)->mem) *__mptr = (ptr); \
(type *)((char*)__mptr - offset_of(type,mem)); \
})
使用举例,定义一个type_t结构体类型,其中包含a,b,c三个成员,t为type_t类型的变量。
此例目的是通过t.b的指针得到t的指针
#include <stdio.h>
#define offset_of(type, mem) ({ \
(size_t)(&(((type*)0)->mem)); \
})
//Linux kernel
#define container_of(ptr, type, mem) ({ \
const typeof(((type*)0)->mem) *__mptr = (ptr); \
(type *)((char*)__mptr - offset_of(type,mem)); \
})
//myself
#define container_of_test(ptr, type, mem) ({ \
(type *)((char*)ptr - offset_of(type,mem)); \
})
typedef struct{
int a;
int b;
int c;
}type_t;
int main(void){
type_t t = {
.a = 1,
.b = 2,
.c = 3
};
int *pb = &(t.b); //pb为变量t中成员b的指针
type_t *pt = container_of(pb, type_t, b); //通过成员b的指针得到变量t的指针pt
printf("成员b在type_t中的偏移量:%d\n",offset_of(type_t, b));
printf("t.c=%d\n",pt->c);
return 0;
}