Container_of (PTR, type, member) is used for the member Member and the member pointer PTR (address) and struct type in a known struct, returns the pointer (the address) of the struct where the member is located, for example, known.
- Struct student {
- Char * Name;
- Int age;
- }
- Int * page = & age;
- Container_of (page, struct student, A. Age); returns the address of.
This method can be implemented in three steps:
0 to calculate. the offset of age in a can be forcibly converted to the struct student format by converting the zero address (struct student *) 0, then (struct student *) 0) -> age is the offset size.
1 known. the age address and the offset in a can be obtained through. age address minus offset to get the address of a, (char *) page-(struct student *) 0)-> Age
2. Forcibly convert the obtained address to the struct student format (struct student *) (char *) page-(struct student *) 0)-> age) that is, the requested pointer.
According to our ideas, the implementation in the kernel is exactly the same as what we think.
- Kernel. h
- # Define container_of (PTR, type, member )({\
- Const typeof (type *) 0)-> member) * _ mptr = (PTR );\
- (Type *) (char *) _ mptr-offsetof (type, member ));})
- # Define offsetof (type, member) (size_t) & (type *) 0)-> Member)
From: http://blog.csdn.net/hellowxwworld/article/details/11072683
This macro is defined in kernel. h;
Prototype: # define container_of (PTR, type, member )({\
Const typeof (type *) 0)-> member) * _ mptr = (PTR );\
(Type *) (char *) _ mptr-offsetof (type, member ));})
PTR is a pointer to a type of variable being used, type is a structure type containing the type pointed to by PTR, and member is a member of the type struct, And the type is the same as the variable type pointed to by PTR.
The function is to calculate the pointer to the type structure variable that contains the variable pointed to by PTR. (Comparison between interfaces)
Implementation idea of this macro: Calculate the offset of the type struct Member member in the struct, And then subtract the offset from the PTR address to obtain the first address of the type struct variable.
Implementation Method of the macro: 1. Define a variable of the same type as the Member member of the type struct using the typeof keyword.
_ Mptr and assign the PTR value to it.
2. Use the macro offsetof (type, member) to obtain the offset of a Member member in the type structure.
(Prototype: offsetof (type, member) (size_t) & (type *) 0)-> Member). defined in stddef. H .)
3. Finally, subtract the _ mptr value from the offset to get the address of the structure variable (also pointer ).
Typeof is a keyword that can be used to reference the type of macro parameters.
From: http://blog.chinaunix.net/uid-24467128-id-2606205.html
(Conversion) kernel container_of (PTR, type, member) Parsing