Understanding the container_of macro
When it comes to managing several data structures in code, you'll almost always need to embed one structure into another and retrieve them at any moment without being asked questions about memory offsets or boundaries. Let's say you have a struct person
, as defined here:
struct person { int age; int salary; char *name; } p;
By only having a pointer on age
or salary
, you can retrieve the whole structure wrapping (containing) that pointer. As the name says, the container_of macro
is used to find the container of the given field of a structure. The macro is defined in include/linux/kernel.h
and looks like the following:
#define container_of(ptr, type, member) ({ \ const typeof(((type *)0)->member) * __mptr = (ptr); \ (type *)((char *)__mptr - offsetof(type, member)); })
Don't be afraid of the pointers; just see them as follows:
container_of(pointer, container_type, container_field);
Here are the elements of the...