• Immutable Page
  • Info
  • Attachments

MagicMacros

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/web/content/view/94/9/

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.

Tell others about this page:

last edited 2008-04-02 18:31:55 by CliffBrake