Linux kernel design patterns - part 2
Posted Jun 13, 2009 13:21 UTC (Sat) by
johill (subscriber, #25196)
Parent article:
Linux kernel design patterns - part 2
The fourth paragraph makes it sound like the kernel always favours opening up structs/data types over making them opaque (abstract). I disagree with this assertion, there can be value in making structures opaque, if only to guarantee properly locked access or deter abuse of visible parts of structures.
Of course, the examples you give are perfectly valid examples where there is no value in making things opaque -- abuse is unlikely, performance concerns require using inlines and similar -- however there are also many examples in the kernel for exactly the opposite.
In code I maintain, I have often combined both approaches, like this:
public.h:
struct foo {
int public;
u8 priv[] __align(sizeof(void*));
};
struct foo *foo_alloc(int privsz);
void foo_destroy(struct foo *f);
foo_do_something(struct foo *f);
internal.c:
struct internal_foo {
int internal;
/* ... */
/* keep last */
struct foo pub;
};
struct foo *foo_alloc(int privsz)
{
struct internal_foo *res = kzalloc(sizeof(*res) + privsz);
if (!res)
return NULL;
return &res->pub;
}
/* etc */
This pretty much combines the best of both worlds -- purely internal details are invisible to API users, and members that are part of the API and can safely be used by API users are made public.
(
Log in to post comments)