Posts

Showing posts with the label container_of macro

Understanding container_of macro of Linux Kernel

Image
container_of macro is the macro you see almost in most of driver code. Search of "container_of" macro in drivers folder of Linux Source code gave more than 10 k results. What is the use of container_of macro? Given a structure having many members. The container_of macro will give the address of the structure when you pass the address of one of the member variable of that structure. Definition: container_of macro is defined in linux/kernel.h. ({ void *__mptr = (void *)(ptr); ((type *)(__mptr - offsetof(type, member))); }) To understand these two lines of the macro, we need to get familiar with the following concepts. typeof() offsetof() Compound Statements 1. typeof():  It is a very useful operator helpful to find out the type of the argument at run time. Using typeof we can write a simple macro which can work for multiple types. For example the swap function defined in kernel.h 2. offsetof(type, member): The offsetof() returns the off...