1.container_of宏的定义及实现
1> Container_of在Linux内核中是一个常用的宏,用于从包含在某个结构中的指针获得结构本身的指针,通俗地讲就是通过结构体变量中某个成员的首地址进而获得整个结构体变量的首地址。2>接口:
container_of(ptr, type, member)
-->ptr:表示结构体中member的地址
-->type:表示结构体类型
-->member:表示结构体中的成员通过ptr的地址可以返回结构体的首地址
3> container_of的实现:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
其实它的语法很简单,只是一些指针的灵活应用,它分两步:
第一步,首先定义一个临时的数据类型(通过typeof( ((type *)0)->member )获得)与ptr相同的指针变量__mptr,然后用它来保存ptr的值。
说明:typeof是GNU C对标准C的扩展,它的作用是根据变量获取变量的类型《typeof关键字在linux 内核中很常见》
第二步,用(char *)__mptr减去member在结构体中的偏移量,得到的值就是整个结构体变量的首地址(整个宏的返回值就是这个首地址)。
offsetof应用实例
- /* linux-2.6.38.8/include/linux/compiler-gcc4.h */
- #define __compiler_offsetof(a,b) __builtin_offsetof(a,b)
- /* linux-2.6.38.8/include/linux/stddef.h */
- #undef offsetof
- #ifdef __compiler_offsetof
- #define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
- #else
- #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
- #endif
- #include <stdio.h>
- struct test_struct {
- int num;
- char ch;
- float fl;
- };
- int main(void)
- {
- printf("offsetof(struct test_struct, num) = %d\n",
- offsetof(struct test_struct, num));
- printf("offsetof(struct test_struct, ch) = %d\n",
- offsetof(struct test_struct, ch));
- printf("offsetof(struct test_struct, fl) = %d\n",
- offsetof(struct test_struct, fl));
- return 0;
- }
- offsetof(struct test_struct, num) = 0
- offsetof(struct test_struct, ch) = 4
- offsetof(struct test_struct, fl) = 8
2.container_of实例
- /* linux-2.6.38.8/include/linux/compiler-gcc4.h */
- #define __compiler_offsetof(a,b) __builtin_offsetof(a,b)
- /* linux-2.6.38.8/include/linux/stddef.h */
- #undef offsetof
- #ifdef __compiler_offsetof
- #define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
- #else
- #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
- #endif
- /* linux-2.6.38.8/include/linux/kernel.h *
- * 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) );})
- #include <stdio.h>
- struct test_struct {
- int num;
- char ch;
- float fl;
- };
- int main(void)
- {
- struct test_struct init_test_struct = { 99, 'C', 59.12 };
- char *char_ptr = &init_test_struct.ch;
- struct test_struct *test_struct = container_of(char_ptr, struct test_struct, ch);
- printf(" test_struct->num = %d\n test_struct->ch = %c\n test_struct->fl = %f\n",
- test_struct->num, test_struct->ch, test_struct->fl);
- return 0;
- }
- test_struct->num = 99
- test_struct->ch = C
- test_struct->fl = 59.119999
本文深入讲解了Linux内核中container_of宏的定义、实现原理及其使用方法,并通过具体实例展示了如何利用该宏从结构体成员指针获取结构体本身指针。
422

被折叠的 条评论
为什么被折叠?



