为了防止自己忘记记录一下linux内核的offsetof 和 container_of两个函数,先随便定义一个结构体
struct node
{
int a;
short b;
char c[5];
double d;
}
显示offsetof
//求结构体类型TYPE中成员MEMBER距离基准位置的长度
#define offsetof(TYPE, MEMBER) \
((size_t)&((TYPE*)0)->MEMBER)
测试数据如下
container_of
/*
ptr: 是一个结构体变量的成员地址
type: 是结构体类型
member: 是ptr指针指向的成员名
*/
//由结构体变量中成员的内存地址获取结构体变量的内存地址
#define container_of(ptr, type, member) ({ \
const typeof( ((type*)0)->member ) *__mptr = (ptr); \
(type*)( (char*)__mptr - offsetof(type, member) );})