内核中宏 container_of是实现list_head链表机制的重要组成部分,其实现如下:
1 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
2
3 #define container_of(ptr, type, member) ({ \
4 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
5 (type *)( (char *)__mptr - offsetof(type,member) );})
当本人感觉第四行实在不是必要的,完全可以删掉,修改后的container_of宏如下:
1 #define offset_of(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
2
3 #define container_of(ptr, type, member) ({ \
4 (type *) ((char *) ptr - offset_of(type, member)); }) \
并且完全可以实现原有的功能,而且并不需要typeof关键字。
下面贴上我的验证程序:
1 #include
2
3 struct list_head{
4 struct list_head *prev, *next;
5 };
6
7 struct test{
8 int count;
9 struct list_head list;
10 int value;
11 };
12
13
14 #define offset_of(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
15
16 #define container_of(ptr, type, member) ({ \
17 (type *) ((char *) ptr - offset_of(type, member)); \
18 })
19
20 int main()
21 {
22 struct test t = {
23 .count = 1,
24 .list = {
25 .prev = NULL,
26 .next = NULL,
27 },
28 .value = 2,
29 };
30 int result0 = offset_of(struct test, list);
31 printf("&t = %x &t.count = %x &t.list = %x &t.value = %x \n", &t, &t.count, &t.list, &t.value);
32 printf("result0 = %x \n", result0);
33 int result1 = container_of(&t.list, struct test, list);
34 printf("result1 = %x &test = %x \n", result1, &t);
35 struct test *t2 = (struct test *) result1;
36 printf("t.count = %d t.value = %d \n", t2->count, t2->value);
37 return;
38 }
大家有人知道为什么内核中的container_of宏,要那么实现吗?
现在知道了,用于地址类型检查!
阅读(1815) | 评论(0) | 转发(0) |