1. 第一个宏:offsetof用于计算 TYPE 结构体中 MEMBER 成员的偏移位置
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE*)0)->MEMBER)
#endif
仔细一看,编译器到底做了什么?
size_t
类型就是long unsigned int
类型,这句代码的意思不就是C语言里面的强制类型转换形式,将0地址处的值强制转换为TYPE*,然后取得 MEMBER 成员变量处的地址吗?
有问题吗?
直接使用0地址处的值不会导致程序崩溃吗?
下面做个试验:
#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 func1(struct ST* pst)
{
int* pi = &(pst->i); // (unsigned int)pst + 0
int* pj = &(pst->j); // (unsigned int)pst + 4
char* pc = &(pst->c); // (unsigned int)pst + 8
printf("pst = %p\n", pst);
printf("pi = %p\n", pi);
printf("pj = %p\n", pj);
printf("pc = %p\n", pc);
}
void func2()
{
printf("offsetof i: %d\n", offsetof(struct ST, i));
printf("offsetof j: %d\n", offsetof(struct ST, j));
printf("offsetof c: %d\n", offsetof(struct ST, c));
}
int main(int argc, char const *argv[])
{
struct ST s = {0};
func1(&s);
func1(NULL);
func2();
return 0;
}
编译运行结果:
程序并没有崩溃,而是正常的运行完毕了。
其实上面的宏,并没有使用0地址处的值,而是和将 结构体地址 和 成员变量的偏移量地址 做了加法运算,得到成员变量的偏移位置,具体转换在代码中已经注释了。
2. 第二个宏:container_of 用于得到结构体的首地址
(1)拆招分析:({ })
这种语法形式是GNU C编译器的语法扩展,与逗号表达式类似,表达式结果为最后一个语句的值
(2)typeof
是GNU C编译器的特有关键字,只在编译期有效,用于得到变量的类型
(3)原理分析:
(4)这个宏使用({ })
语法进行类型安全检查
#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; // 等价于 int j = i;
const typeof(j)* p = &j; // 等价于 const int* 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;
}
编译运行结果:得到结构体的首地址相同