container_of小例, 仅供复习参考用
1 #include <stdio.h>
2 #include <linux/kernel.h>
3 #include <string.h>
4 #include <strings.h>
5
6 #define offsetof(TYPE,MEMBER) ((int) &((TYPE *)0)->MEMBER)
7 //通过获取结构体中的某个成员的,反推该结构体的指针
8 #define container_of(ptr, type , member) ({ \
9 const typeof(((type *)0)->member) *__mptr = (ptr) ; \
10 (type *)((char *)__mptr - offsetof(type,member)) ;})
11
12
13 typedef struct mystruct
14 {
15 int a;
16 int b;
17 char c;
18 }TEST;
19
20 int main(void)
21 {
22 TEST mytest;
23 memset(&mytest, 0, sizeof(mytest));
24 printf("&mytest = %p\n",&mytest);
25 TEST* p = container_of(&mytest.c, TEST, c);
26 printf("p = %p\n",p);
27 printf("p->a = %d\n", p->a);
28 printf("p->b = %d\n", p->b);
29 printf("p->c = %d\n", p->c);
30 return 0;
31 }
root@ubuntu:/shiyan/shiyan271# gcc shiyan271.c
root@ubuntu:/shiyan/shiyan271# ./a.out
&mytest = 0xbf9c1d9c
p = 0xbf9c1d9c
root@ubuntu:/shiyan/shiyan271# gcc shiyan271.c
root@ubuntu:/shiyan/shiyan271# ./a.out
&mytest = 0xbff1a9ec
p = 0xbff1a9ec
p->a = 0
p->b = 0
p->c = 0
root@ubuntu:/shiyan/shiyan271#