一、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
*/