Macro definitions for Offsetof and container_of in the Linux kernel
#define OFFSETOF (Type, MEMBER) ((size_t) & ((TYPE *) 0)->member)
/**
* 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.
* */
#define CONTAINER_OF (PTR, type, member) ({\
Const typeof (((type *) 0)->member) *__mptr = (PTR); \
(Type *) ((char *) __mptr-offsetof (Type,member));})
Offsetof meaning: Gets the memory location offset of a member variable in a struct relative to the first address of the struct;
Container_of meaning: Gets the memory header address of a struct body based on the memory address of a member variable in the struct.
Offsetof Macro Detailed:
#define OFFSETOF (Type, MEMBER) ((size_t) & ((TYPE *) 0)->member)
1), the parameter type is the type definition of the struct body, member is the struct member variable name;
2), the implementation method comparison trickery: 0 is forced to convert the type of a pointer, and then to the member variable address;
3), code example:
typedef struct
{
int A;
Char b;
void *c;
} off_struct_s;
offsetof ( off_strcut_s, B),
The end result is: Offset a:0 b:4 c:8
CONTAINER_OF Macro Detailed:
#define CONTAINER_OF (PTR, type, member) ({\
Const typeof (((type *) 0)->member) *__mptr = (PTR); \
(Type *) ((char *) __mptr-offsetof (Type,member));})
1), the parameter PTR is the memory address of the struct member, type is the struct type definition, member is the struct member variable name;
2), typeof is the built-in function of the gun compiler series, the function returns the type of the current variable;
3),const typeof (((type *) 0)->member) *__mptr = (PTR); This row defines a pointer variable __mptr for a member type, and the value is initialized to PTR ( Note: Here the type is also 0 cast);
The result of the operation must be &stru and PTR memory address is the same, this example is only to make a proof that the actual use of the first is not aware of the structure of the first address, need to be the structure of the variable address to calculate the structure of the first address.
In fact, it is very simple to sum up, in order to calculate the structure of the pointer according to the pointer of a struct variable, only the current variable pointer minus the variable to the first of the structure of the offset (base = Ptr-offset).
Definitions of Offsetof and CONTAINER_OF macros in Linux