offset_of 与 container_of 用法举例

先看宏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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值