<gu**********@g ooglemail.comwr ote in message
news:11******** **************@ w5g2000hsg.goog legroups.com...
hi,
i have a struct in c# that is containing Int32 member and Double
member.
when i try to get the size of it i get size of 16 bytes, while i was
expecting to receive 12. (Int32- 4 bytes, Double - 8 bytes)
does anyone have any ideas why it occur?
The size given is the size of the struct as it would be marshaled to
unmanaged code, this is not necessarily the size on the stack.
Per default, struct elements are aligned at their natural bounds in memory,
your struct could for instance look like this on the stack (32 bit OS) :
address type
0x120104 int32
0x120108 double
occupying 12 bytes, both elements are aligned at their natural bounds, but
it could also look like this:
address type
0x120108 int32
0x120110 double
and as such, occupy 16 bytes. The marshaled struct however, will per default
get laid-out like this:
0x-----0 int32
0x-----8 double
so here the size is 16 due to alignment of the double element at his natural
bound (a multiple of sizeof(double)) .
You can control the way structs are aligned and packed(when marshaled), by
means of the StructLayout attribute Pack or by applying an explicit layout
(LayoutKind.Exp licit).
Willy.