一个简要的示例说明Linux内核的container_of 的用法,很简洁,不多说了,直接附上代码,自己gcc container_of.c -o container_of.out ; ./container_of.out 吧。如被转载,请附上原转载地址,谢谢!
//container_of.c
#include <stdio.h>
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
#define container_of(ptr, type, member) ({const typeof( ((type *)0)->member ) *__mptr = (ptr);(type *)( (char *)__mptr - offsetof(type,member) );})
struct _T
{
int n;
int m;
char in;
char *str;
int x;
int y;
}t;
void main()
{
int *r=&t.m;
struct _T *p;
t.n=10;
t.m=20;
t.in='a';
t.str="zhong";
t.x=100;
t.y=200;
p=container_of(r,struct _T,m);
printf("%s\n",p->str);
}