container_of介绍

container_of介绍

一、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) );})

1、参数介绍

  ptr   :结构体中某个成员的地址
  type  :结构体的类型
  member :结构体中某个成员的名称

2、源码中的宏介绍

  typeof(),获得变量或表达式类型。
  offsetof(),获取结构体中某个成员相对于该结构体首元素地址的偏移量。

三、container_of应用

#include<stdio.h>
#include<stddef.h>
#define container_of(ptr, type, member) ({                      \
        const typeof(((type *) 0)->member) *__mptr = (ptr);     \
        (type *) ((char *) __mptr - offsetof(type, member));})
        struct  BOOK{
 int id;
 char name[10];
 float price;
};  
int main()
{
   struct BOOK book,*p;
   p=container_of(&book.price,struct  BOOK,price);
   printf("struct STORE 结构体首地址0x%x\n",&book);
   printf("container_of 返回的地址0x%x\n",p);
   return 0;
}
/*
运行结果
struct STORE 结构体首地址0xbfbdfaa0
container_of 返回的地址  0xbfbdfaa0
*/

  
  
  
  
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值