今天我们来看看 Linux 中的两个经典的宏:offsetof 与 container_of。
下面我们先来看看它们两个的宏定义,如下
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE*)0)->MEMBER)
#endif
#ifndef container_of
#define container_of(ptr, type, member) ({ \
const typeof(((type*)0)->member)* __mptr = (ptr); \
(type*)((char*))__mptr - offsetof(type, member); })
#endif
要想看懂这两个宏,我们就先来看看编译器做了什么?
把地址 0 强制类型转换成一个 type 类型的结构体指针
offsetof 是用于计算 TYPE 结构体中 MEMBER 成员的偏移位置。编译器清楚的知道结构体成员变量的偏移位置,通过结构体变量首地址与偏移量定位成员变量。
下面我们通过测试代码来进行说明
#include <stdio.h>
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE*)0)->MEMBER)
#endif
struct ST
{
int i; // 0
int j; // 4
char c; // 8
};
void func(struct ST* pst)
{
int* pi = &(pst->i); // 0
int* pj = &(pst->j); // 4
char* pc = &(pst->c); // 8
printf("pst = %p\n", pst);
printf("pi = %p\n", pi);
printf("pj = %p\n", pj);
printf("pc = %p\n", pc);
}
int main()
{
struct ST s = {0};
func(&s);
func(NULL);
printf("offset i: %d\n", offsetof(struct ST, i));
printf("offset j: %d\n", offsetof(struct ST, j));
printf("offset c: %d\n", offsetof(struct ST, c));
return 0;
}
我们看到 pst 和 pi 打印的地址值是一样的,j 和 c 分别加 4。以 NULL 为参数传进去更加看的明显,而直接调用 offsetof 宏,它的效果和 NULL 是一样的。由此,它的作用就显而易见了,用于获取 TYPE 结构体中的 MEMBER 的偏移量。
下来我们来看看 container_of 宏,首先讲解下({ }),它是 GNU C 编译器的语法扩展,它与逗号表达式的作用类似,结果为最后一个语句的值。如下所示
typeof 是 GNU C 编译器特有的关键字,它只在编译器生效,用于得到变量的类型。用法如下
最后的原理如下图所示:
#include <stdio.h>
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE*)0)->MEMBER)
#endif
#ifndef container_of
#define container_of(ptr, type, member) ({ \ //指针定义不能嵌套在宏定义中,所以引用圆括号嵌套花括号。
const typeof(((type*)0)->member)* __mptr = (ptr); \ //宏定义是被预处理器处理,加这条语句防止参数类型不同。
(type*)((char*)__mptr - offsetof(type, member)); })
#endif
#ifndef container_of_new
#define container_of_new(ptr, type, member) ((type*)((char*)(ptr) - offsetof(type, member)))
#endif
struct ST
{
int i; // 0
int j; // 4
char c; // 8
};
void method_1()
{
int a = 0;
int b = 0;
int r = (
a = 1,
b = 2,
a + b
);
printf("r = %d\n", r);
}
void method_2()
{
int r = ( {
int a = 1;
int b = 2;
a + b;
} );
printf("r = %d\n", r);
}
void type_of()
{
int i = 100;
typeof(i) j = i;
const typeof(j)* p = &j;
printf("sizeof(j) = %d\n", sizeof(j));
printf("j = %d\n", j);
printf("*p = %d\n", *p);
}
int main()
{
method_1();
method_2();
type_of();
struct ST s = {0};
char* pc = &s.c;
int e = 0;
int* pe = &e;
struct ST* pst = container_of(pc, struct ST, c);
printf("&s = %p\n", &s);
printf("pst = %p\n", pst);
return 0;
}
原生的 container_of 宏写法虽然复杂点,但是它的安全性是最高的。
小结:
— 编译器清楚的知道结构体成员变量的偏移位置;
— ({ }) 与逗号表达式类似,结果为最后一个语句的值;
— typeof 只在编译期生效,用于得到变量的类型;
— container_of 使用 ({ }) 进行类型的安全检查。