Some time when I start with kernel development I couln’t understand how container_of macro from kerne lworks.
Some days ago there were and post on kernelnewbies list about using this. This gives me a signal to finally understand what’s going on. I try to write simple user space application with container_of macro using.
Code:
#include <stdio.h>
#include <stdlib.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define CONT(prt, type, mem) container_of((prt), type, mem)
struct test {
int a;
};
struct m {
int b;
struct test t;
int c;
};
int main(int argc, char *argv[])
{
/* existing structure */
struct m *ma;
ma = malloc(sizeof(struct m));
ma->t.a = 5;
ma->b = 3;
/* pointer to existing entry */
struct test *te = &ma->t;
struct m *m = CONT(te, struct m, t);
printf("m->b = %d\n", m->b);
return EXIT_SUCCESS;
}
At the beginnig is defined offsetof and container_of macros taken from kernel source.
We will use structure m which encapsulate structure test.
Container of macro is used to get a pointer to beginning of structure which contain element by type.
In our case we have a element t (in struct main) and would like to get pointer to main structure.
Input arguments will be : prt – pointer to element, type – type of element, elemet.
Note: this code is just for understanding how it works, don’t comment it
.
You can find very good description at : http://www.kroah.com/log/linux/container_of.html
Marek



I guess that your explanation is confusing. If you use “element” to represent “struct test t”. Then “prt” is a pointer to the element (you are right); “type” is the type of the struct which the element is embedded in (ie, struct m. You got wrong here.); “element” is the name of “struct test” which is “t” (you are right).