4 ms·
The last part is pretty cool (the first bit has been supported by GCC for years), though it would be even more helpful to be able to do the reverse concisely -
by pmjordan 16y ago
The last part is pretty cool (the first bit has been supported by GCC for years), though it would be even more helpful to be able to do the reverse concisely - convert a pointer to the contained struct to a pointer to the containing one. In my C code I invariably use (something similar to) the container_of() macro used in the Linux kernel [1]. The primary use is in callbacks associated with a particular object that can be embedded in larger structures.
Right now, say a library I'm using exposes this:
struct lib_struct {
int foo;
char* bar;
};
typedef void (*lib_callback)(struct lib_struct*);
extern void lib_fn(struct lib_struct* obj, lib_callback cb);
If I want to use that in one of my own data structures:
struct my_struct {
struct lib_struct lib_st;
int my_own_data;
};
static void my_callback(struct lib_struct* lib_st)
{
// plan9 extension does not appear to help here...
struct my_struct* me = container_of(lib_st, struct my_struct, lib_st);
printf("%i\n", me->my_own_data);
}
/* elsewhere... */
struct my_struct* m = /* ... */;
// ... though it would here:
lib_fn(&m->lib_st, my_callback);
It'd be handy to be able to condense the container_of line somewhat, while maintaining (some) type safety.
[1] http://www.kroah.com/log/linux/container_of.html http://www.kroah.com/log/linux/container_of.html - I use a similar macro that preserves NULL pointers.