/*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*/#undefOffsetof#ifdef __compiler_offsetof#defineOffsetof (Type,member) __compiler_offsetof (Type,member)#else#defineOffsetof (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 was embedded in. * @member: The name of the member within the struct. * */#defineContainer_of (PTR, type, member) ({Const typeof((Type *)0)->member) *__mptr =(PTR); (Type*)( (Char*) __mptr-offsetof (Type,member));}) #include<stdio.h>structtest_struct {intnum; Charch; floatFL;};intMainvoid){ structTest_struct init_test_struct = { About,'C',59.12 }; Char*char_ptr = &init_test_struct.ch; structTest_struct *test_struct = container_of (Char_ptr,structtest_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;}
Common macro container_of in the Linux kernel