Interesting C header translation problem

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Tue Oct 30 02:41:42 PDT 2012


Came across this:

    #ifdef __GNUC__
        #define PACKED __attribute__((packed))
    #else
        #define PACKED
    #endif

    typedef enum {
        // Lots o' stuff
    } PACKED my_enum_t;

    typedef struct {
        // Lots o' stuff
        const void *ptr;
    } PACKED my_struct_t;

There are a handful of interesting (read: annoying ;) ) problems that
are (*ahem*) packed into that:

1. Totally different ABI based on whether or not the **C** side was
compiled with a GNU compiler.

2. How to do conditional "align(1)" with minimal ugliness.

3. WTF does it even mean to have a packed enum?

4. Having a pointer at the end of a packed struct is asking for trouble
according to D's docs ("The garbage collector assumes that pointers and
references to gc allocated objects will be on size_t byte boundaries.
If they are not, undefined behavior will result.") Probably nothing
that can be done about this one, though, other than just expect the
user to be careful.

5. From what I can gather from GCC and DMD docs, it sounds like
__attribute__((packed)) means:

    align(1) struct my_struct_t{
        align(1):
        // blah, blah, members
    }

BUT, are there any other...ummm..."fun" surprises that could pop up and
need to be taken into account?

6. The easy one: I'm pretty sure "const void *ptr" translates to
"const(void)* ptr", right?

For the moment, my "solution" is to just include a note saying "Don't
compile the *.c files with __GNUC__ defined" ;) But what would be the
best realistic way to handle these issues? Any established practices?



More information about the Digitalmars-d-learn mailing list