很早前之前看的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 *))->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 *))->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 =;
child->b =;
child->parent.a =;
child->parent.b =; 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); }