KernelNewbies:

This page is intended to describe some magic macros used in kernel.

container_of

The container_of macro is defined in include/linux/kernel.h as following:

/**
 * 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 is 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) );})

GregKH described the inner working of this macro in an article on linuxjournal.com [1] and in his weblog [2].

[1] http://www.linuxjournal.com/article/5783

[2] http://www.kroah.com/log/linux/container_of.html

Another example of how to use this macro: http://bec-systems.com/site/115/the-linux-kernel-container_of-macro

ARRAY_SIZE

Also defined in include/linux/kernel.h ARRAY_SIZE(x) is used to get the number of elements in an array.

#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

Therefor it divides the size of the array by the size of the first array element.

KernelNewbies: MagicMacros (last edited 2021-01-12 06:49:14 by RandyDunlap)