In_of macro definition, contain_of macro
Container_of is a common macro in Linux kernel. It is used to obtain the pointer of the structure from the pointer contained in a structure, generally, the first address of a member in the struct variable is obtained to obtain the first address of the entire struct variable.
Implementation Method:
Container_of (ptr, type, member );
In fact, its syntax is very simple, but some pointers are used flexibly. It consists of two steps:
Step 1: first define a temporary data type (obtained through typeof (type *) 0)-> member) with the same pointer Variable _ mptr as ptr, use it to save the ptr value.
Step 2: Use (char *) _ mptr to subtract the offset of member in the struct. The obtained value is the first address of the entire struct variable (the return value of the entire macro is the first address ).
The difficulty in the syntax is how to get the offset of the member to the struct?
For example, in Listing 1:
1 #include <stdio.h> 2 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) 3 #define container_of(ptr, type, member) ({ \ 4 const typeof( ((type *)0)->member ) *__mptr = (ptr); \ 5 (type *)( (char *)__mptr - offsetof(type,member) );}) 6 struct test_struct { 7 int num; 8 char ch; 9 float f1;10 };11 int main(void)12 {13 struct test_struct *test_struct;14 struct test_struct init_struct ={12,'a',12.3};15 char *ptr_ch = &init_struct.ch;16 test_struct = container_of(ptr_ch,struct test_struct,ch);17 printf("test_struct->num =%d\n",test_struct->num);18 printf("test_struct->ch =%c\n",test_struct->ch);19 printf("test_struct->ch =%f\n",test_struct->f1);20 return 0;21 }