- 论坛徽章:
- 5
|
本帖最后由 T-Bagwell 于 2011-07-07 08:58 编辑
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #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) );})
- struct example{
- unsigned char ea;
- int eb;
- int ec;
- };
- int main()
- {
- struct example *example=malloc(sizeof(struct example));
- memset(example,0,sizeof(struct example));
- printf("%p\n",example);
- printf("%p\n",&(example->ec));
- printf("%p\n",(void *)offsetof(struct example,ec));
- printf("%p\n",container_of(&(example->ec),struct example,ec));
- free(example);
- example=NULL;
- return 0;
- }
复制代码 转自我的blog
主要是因为typeof这个功能,member的偏移,计算整体大小,然后就知道struct地址了,这个地址就是结构体的入口了 |
|