layoutstructdportabilityinterfacing

Is the exact layout of D structs defined?


Is the exact layout of D structs defined? That is, the exact offset of every member defined and in a compiler-independent way? That would mean that the compiler would, fortunately or unfortunately, depending on your needs, be forbidden to reorder fields to get optimal packing of smaller items and minimise all offsets.


Solution

  • It is indeed illegal for the D compiler to rearrange members of a struct (though it can for classes). It's important that the compiler not rearrange members for structs, because structs are supposed to be able to be used for low-level stuff that requires specific memory layouts. It's also the case that structs need to be able to interact with C code, so they need to match what you'd get it in C (at least when extern(C) is used). So, structs definitely don't get their members rearranged. In addition, you can specific the alignment of members via the align attribute, so you have full control over the layout of a struct.

    Now, the default layout can differ depending on the architecture (e.g. 64-bit pointers take up more space than 32-bit pointers, which will affect how the struct members are packed), but it should match what you get in C on that architecture.