Thread overview
Re: Struct sizes - converting C to D
Apr 21, 2004
Walter
Apr 21, 2004
Adam Harper
Apr 21, 2004
Adam Harper
April 21, 2004
Which C compiler are you using?

"Adam Harper" <a-news-d@harper.nu> wrote in message news:20040420191949.4fb327f7.a-news-d@harper.nu...
> I've been using D quite happily know for a number of months (great job Walter, keep it up!) and have recently been converting more and more C header files into D imports so that I can write the little programs/utilities that I would have normally written in C in D.
>
> One header file in particular has thrown up an anomaly that I can't figure out.  It concerns the size of a struct, after converting the struct definition to D the .size property reports a value one lower than that reported by C.
>
> I've attached two simple source files (one C, one D) that show what I mean.  The output from the C file is:
>
> > Test.size = 46
> > Test member offsets:
> >         field1=0
> >         field2=26
> >         field3=28
>
> With D reporting:
>
> > Test.size = 45
> > Test member offsets:
> >         field1=0
> >         field2=26
> >         field3=28
>
> I sure it's something simple I'm missing, and if any one out there can help enlighten me it'd be greatly appreciated.
>
> --
> Adam
>


April 21, 2004
Walter wrote:
> Which C compiler are you using?

I've tested it using GCC 3.3.3 (on Linux) and DMC 8.29n (on Windows). On both occasions DMD 0.82 was used to compile the D version.  The command lines used were as follows:

GCC:
> gcc structc.c -ostructc

DMC:
> dmc structc.c

DMD:
> dmd structd.d
April 21, 2004
Further investigation reveals that the struct size is incorrect only when:

  - The last member of the struct is a static char array
    (e.g. char[2] abc)
  - The preceding member is a short, int, long, float or double (possibly
    anything other than char's or char[n]'s, I only tested those).

The size difference is linked to the size of the preceding member, e.g. for shorts there is a one byte difference, for ints and floats a three byte difference and for longs and doubles a seven byte difference.

Examples of problem structs:

 > struct Test{short a; char[2] b;};
 > struct Test{char[2] a; int b; char[3] c;};

Examples of OK structs:

 > struct Test{short a; char[2] b; char[3] c;};
 > struct Test{double a; char b; char[2] c;};

(Note: I seem to have accidentaly cancelled my previous message (still
getting the hang of this new fangled Thunderbird thing), so I've
attached a slightly edited version of the files to this message.)

--
Adam