Thread overview | ||||||
---|---|---|---|---|---|---|
|
July 01, 2015 wrong struct alignment | ||||
---|---|---|---|---|
| ||||
i have the following struct, and i expect it to have 30 bytes but sizeof tells me it has 32 bytes. dmd seems to still use 4byte alignment altough i specified to align 2bytes. struct netadr_t { align(2): int type; // 0 int scope_id; // 4 short port; // 8 // <-- this is 4 bytes instead of 2 int sock; // 10 union { ubyte[4] ip; // 14 ubyte[10] ipx; ubyte[16] ip6; } } since i'm interfacing with a c library the struct layout has to be equal :( |
July 01, 2015 Re: wrong struct alignment | ||||
---|---|---|---|---|
| ||||
Posted in reply to dd0s | On Wednesday, 1 July 2015 at 20:01:08 UTC, dd0s wrote:
> int scope_id; // 4
> short port; // 8 // <-- this is 4 bytes instead of 2
That's expected because scope_id takes 4 bytes, so port has to be at 8 so it doesn't overlap the preceding int.
The extra two bytes you see in sizeof are probably at the *end* of the struct, not between the members.
To get rid of them, out align(2) on the outside too:
align(2)
struct yourthing {
align(2):
members
}
That will trim the size. The align inside the struct packs the members, but still pads the end (which means an array of these structs will be aligned on the word boundary). The align on the outside removes the padding at the end, meaning an an array of the structs would be packed too.
|
July 01, 2015 Re: wrong struct alignment | ||||
---|---|---|---|---|
| ||||
Posted in reply to dd0s | On Wednesday, 1 July 2015 at 20:01:08 UTC, dd0s wrote:
> i have the following struct, and i expect it to have 30 bytes
> but sizeof tells me it has 32 bytes. dmd seems to still use 4byte alignment altough i specified to align 2bytes.
>
> struct netadr_t {
> align(2):
> int type; // 0
> int scope_id; // 4
> short port; // 8 // <-- this is 4 bytes instead of 2
> int sock; // 10
>
> union {
> ubyte[4] ip; // 14
> ubyte[10] ipx;
> ubyte[16] ip6;
> }
> }
>
> since i'm interfacing with a c library the struct layout has to be equal :(
Disclaimer: My understanding of all things alignment is limited.
`pragma(msg, netadr_t.sock.offsetof);` prints "10LU", so port seems to really only take 2 bytes. The struct itself has padding at the end. You can eliminate that with an `align(1)` on the struct:
----
align(1) struct netadr_t {
align(2):
...
}
----
|
Copyright © 1999-2021 by the D Language Foundation