offset of 和 container of 解析

   在Linux源码中,经常看到大名鼎鼎offsetof 和 container of 的宏定义,这里就此进行解析,并做了实验验证用途,仅用于自己参考记录。

  1. offsetof
  主要作用是获取类型的偏移量
  定义如下:

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

  这里我们一层一层分析下offsetof
  (1)首先是TYPE *0定义了一个TYPE类型的指针,指针的偏移地址为0
  (2)然后从0位置开始选择我们需要看到偏移量的成员MEMBER
  (3)对其取址,得到的即为偏移量

  2. container_of
  主要作用是根据结构体中某成员获取该结构体的首地址指针
  定义如下:


/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:        the pointer to the member.
 * @type:       the type of the container struct this is embedded in.
 * @member:     the name of the member within the struct.
 *
 * It takes three arguments – a pointer, type of the container,
 * and the name of the member the pointer refers to. 
 * The macro will then expand to a new address pointing 
 * to the container which accommodates the respective member. 
 */
#define container_of(ptr, type, member) ({                      \
	const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
	(type *)( (char *)__mptr - offsetof(type,member) );})

  第一行看起来和offsetof类似,只是少了取址,多了类型转换和赋值,其实是用一个__mptr代替ptr进行操作,以免误操作。

  第二行这里用字符指针是因为字符类型为1个字节,所以可以方便的计算出__mptr,即ptr的地址位置,然后减去其偏移量,得到的即为TYPE类型的首地址对应的指针。

测试代码如下:

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

typedef struct data_list
{
	int  test_int_data;
	char test_char_data; 
	struct list_head list;
}data_list;


int main()
{	
	data_list data;
	data.test_int_data = 123;
	data.test_char_data = 'a';
	
	/* We test offsetof here*/
	printf("\n-------We test the offset marco-------\n");
	printf("offset of test_int_data = %lu\n", offsetof(data_list, test_int_data));
	printf("offset of test_char_data = %lu\n", offsetof(data_list, test_char_data));
	printf("offset of list_head = %lu\n", offsetof(data_list, list));

	/*We test container_of here*/
	printf("\n-------We test the container_of marco-------\n");
	data_list *ptr;
	ptr = container_of(&(data.test_int_data), data_list, test_int_data);
	printf("We define a new pointer ptr to struct data_list\n");
	printf("After container_of, the values are as follow\n");
	printf("ptr->test_int_data = %d\n", ptr->test_int_data);
	printf("ptr->test_char_data = %c\n", ptr->test_char_data); 

	return 0;
}

欢迎关注本人公众号,公众号会更新一些不一样的内容,相信一定会有所收获。
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ch_ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值