LWN.net Logo

Object-oriented design patterns in the kernel, part 2

Object-oriented design patterns in the kernel, part 2

Posted Jun 7, 2011 22:29 UTC (Tue) by cmccabe (guest, #60281)
In reply to: Object-oriented design patterns in the kernel, part 2 by nix
Parent article: Object-oriented design patterns in the kernel, part 2

I don't think any macros are really needed, just something like this:

struct base {
int a;
int b;
char end[0] __attribute__((aligned(4)));
};

struct derived1 {
int a;
};

struct derived2 {
char b;
};
Then you have stuff like this:
void foo(struct base *b) {
    if (type == DERIVED1) {
        struct derived1 *d = (struct derived1*)b->end;
        ...
    }
}
It isn't as nice as C++, but it's ok.

Flexible array members were standardized in C99. Every compiler can do it, but I don't know if the syntax for forcing alignment is standardized yet.


(Log in to post comments)

Object-oriented design patterns in the kernel, part 2

Posted Jun 8, 2011 4:52 UTC (Wed) by jzbiciak (✭ supporter ✭, #5246) [Link]

I don't know if the syntax for forcing alignment is standardized yet.

What if you just made it an array of "double" or "long double"? Or, an array of a union of all of the "large" types, so you're guaranteed to get the most restrictively aligned type on the platform?

typedef union
{
    long long   ll;
    double      d;
    long double ld;
    void       *vp;
    void      (*fp)(void);  /* function pointer */
} align_u;

Then replace char end[0] __attribute__((aligned(4))); with align_u end[0];. Wouldn't that work?

Object-oriented design patterns in the kernel, part 2

Posted Jun 8, 2011 13:16 UTC (Wed) by nix (subscriber, #2304) [Link]

That does indeed work and is exactly what I did. A hallowed ancient trick: I don't know *how* long ago I first saw it. Decades back.

Object-oriented design patterns in the kernel, part 2

Posted Jun 8, 2011 13:14 UTC (Wed) by nix (subscriber, #2304) [Link]

Ah yes. You have access to flexible array members and can assume that you're using GCC. Alas, when I perpetrated this trick I could assume neither of these, so needed a suitable union as a final member to ensure correct alignment.

The macros are just to make things less horrendously unreadable. :)

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds