Browse Source Download (without any required ccan dependencies)
container_of
routine for upcasting
Rusty Russell <rusty@rustcorp.com.au>
It is often convenient to create code where the caller registers a pointer to a generic structure and a callback. The callback might know that the pointer points to within a larger structure, and container_of gives a convenient and fairly type-safe way of returning to the enclosing structure.
This idiom is an alternative to providing a void * pointer for every callback.
#include <stdio.h>
#include <ccan/container_of/container_of.h>
struct timer {
void *members;
};
struct info {
int my_stuff;
struct timer timer;
};
static void register_timer(struct timer *timer)
{
//...
}
static void my_timer_callback(struct timer *timer)
{
struct info *info = container_of(timer, struct info, timer);
printf("my_stuff is %u\n", info->my_stuff);
}
int main(void)
{
struct info info = { .my_stuff = 1 };
register_timer(&info.timer);
// ...
return 0;
}
CC0 (Public domain)