C struct -> D struct (alignment hacks)

Jarrett Billingsley jarrett.billingsley at gmail.com
Wed Feb 4 12:04:16 PST 2009


On Wed, Feb 4, 2009 at 2:55 PM, Mike <vertex at gmx.at> wrote:
> Hi!
>
> I'm in the process of translating some C headers (still ffmpef -> libavcode
> and libavformat) to D and there are some really ugly structs in the C
> headers which I'm trying to translate.
>
> - C -
>
> typedef struct xy
> {
>    int a:1;
>    int b:2;
>    int c;
> }
>
> - D -
>
> struct xy
> {
>    align (1)
>    {
>        int a;
>    }
>    align (2)
>    {
>        int b;
>    }
>    int c;
> }
>
> Are those definitions equivalent?

Nope.  The C struct is defining a bitfield; a and b will actually be
contained within a single 4-byte field.  Your D version defines three
integers.

Unfortunately the C specification does not specify any required
ordering for bitfields, padding, ordering etc.  Fortunately, most
compilers just put them in order, starting from the lowest bits.

What you'll have to do, then, is put a single int field that
corresponds to the C struct's bitfields.  Then, have methods which
shift and mask the bits to get and set the individual bitfields.  htod
will do this for you, if you're on windows and just want to run an .h
file containing that struct through it.


More information about the Digitalmars-d-learn mailing list