Linux内核中的container_of宏
Linux内核中的container_of宏
在看LDD第3章scull驱动的时候,遇到了container_of宏。这个东东会经常在内核中出现,原型定义在linux/include/linux/kernel.h中- #define container_of(ptr, type, member) ({ \
- const typeof( ((type *)0)->member ) *__mptr = (ptr); \
- (type *)( (char *)__mptr - offsetof(type,member) );})
为了说明这个宏是干什么用的,我编写了一个应用层的小程序。在应用层同样定义这样的一个宏,然后使用它。
- <span style="font-size:13px;"></span><pre class="cpp" name="code">#include<stdio.h>
- #include<stdlib.h>
- #include<stddef.h>
- #define container_of(ptr, type, member) ({ \
- const typeof( ((type *)0)->member ) *__mptr = (ptr); \
- (type *)( (char *)__mptr - offsetof(type,member) );})
- struct test
- {
- int aint;
- char array[20];
- char *pointer;
- };
- int main()
- {
- struct test test_example;
- printf("sizeof test is %d\n", sizeof(test_example));
- printf("address of test_example is %p\n", &test_example);
- printf("address of test_example according to 'array' %p\n", container_of(test_example.array, struct test, array));
- printf("address of test_example according to 'pointer' %p\n", container_of(&test_example.pointer, struct test, pointer));
- return 0;
- }
编译、执行,输出的结果如下图所示:
不用我多说了吧,container_of的作用在于,给定某结构体中字段的地址,能够获取该结构体的起始地址。
评论暂时关闭