container_of 例子说明

12 篇文章 0 订阅

很早前之前看的linux内核,一直想把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.
 *
 */
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})


作用:返回member成员对应的所在的父结构体指针。下面的例子就通过child变量的一个成员地址获取到child变量的地址,以便访问child变量的其他成员


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


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


#define container_of(ptr, type, member) ({			\
	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
	(type *)( (char *)__mptr - offsetof(type,member) );})


struct parentStruct{
	int a;
        int b;
};


struct childStruct{
	struct parentStruct parent;
	int a;
        int b;
};


void main(void){


	struct childStruct * child =(struct childStruct*) malloc(sizeof(struct childStruct));
	child->a =100;
	child->b =1000;
	child->parent.a =200;
	child->parent.b =2000;


	struct parentStruct *parent = &child->parent;


	struct childStruct * child1 = container_of(parent,struct childStruct,parent);


	printf("%d,%d\n",child->a,child1->a);
	printf("%d,%d\n",child->b,child1->b);
	printf("%d,%d\n",child->parent.a,child1->parent.a);
	printf("%d,%d\n",child->parent.b,child1->parent.b);
	printf("%#x,%#x\n",child,child1);


	free(child);
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

john_liqinghan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值