69,374
社区成员
发帖
与我相关
我的任务
分享
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
/**
* 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) );})
struct Node {
int a;
int b;
};
struct Node anode = {12, 34};
int *q = &(anode.a);
struct Node * pnode = { const int *m = (q); (struct Node *) ((char *) m - offsetof(struct Node, q));}
struct Node {
int a;
int b;
};
struct Node anode = {12, 34};
int *q = &(node,a);
sruct Node * pnode = { const int *m = (q); (struct Node *) ((char *) m - offsetof(struct Node, q));}
比如说
int x = {const double y = 89; (int) 3.6;}
这个应该是编译不通过的。。
但是这个宏定义为在内核里为什么可以
q = container_of(a, struct b, c);
这样用呢??
typedef struct
{
int a;
float b;
}Test_Struct;
#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) );})
Test_Struct test;
test.a = 123;
test.b = 23.456;
container_of(&test.b, Test_Struct, b);
struct A
{
int a;
int b;
}
size_t o = offsetof(A, b);
A *p = (A*)malloc(A);
int *pB = p->b;
那么 ((char*)pB-(char*)p) == o
所以 p == (A*)((char*)pB - o), (A*)((char*)pB - o) == p。
container_of(pB, A, b)
展开后为
const typeof( ((A*)0)->b )* __mptr = pB;
(A*)((char*)__mptr - offsetof(A, b))
因为 __mptr = pB, offsetof(A, b) = o
所以 上面的式子可化简为
(A*)((char*)pB - o) => p