今天我们来看看 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
要想看懂这两个宏,我们就先来看看编译器做了什么? 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;
}
我们来编译看看结果
编译的时候报了 4 个警告,但是不影响我们的输出,看看运行结果
上面的两个输出 r 的值是一样的,它们的写法是等价的。用 container_of 宏调用的时候,s 和 pst 的地址值是一样的。那么我们用自己定义的 container_of_new 宏来调用 pe 试试呢?看看结果
编译的时候已经给出警告了,说 pc 的类型是不对的。然后我们来运行看看结果
我们发现最后打印的 s 和 pst 的值竟然是不一样的。由此可以看出,原生的 container_of 宏写法虽然复杂点,但是它的安全性是最高的。通过今天对 offsetof 与 container_of 宏的剖析,总结如下:1、编译器清楚的知道结构体成员变量的偏移位置;2、({ }) 与逗号表达式类似,结果为最后一个语句的值;3、typeof 只在编译期生效,用于得到变量的类型;4、container_of 使用 ({ }) 进行类型的安全检查。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。