struct size error

  • Thread starter Thread starter guy.gorodish
  • Start date Start date
G

guy.gorodish

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?
 
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?

From what I can tell dot net pads the size of a struct to be a multiple of
the largest data type. A struct like this

struct x
{
public int16 a;
public byte b;
}

will be 4 bytes and this:

struct y
{
public int32 a;
public byte b;
}

will be 8. And yours is 16. The order does not seem to be important. This
would make sense so that structs stored in arrays align to certain
boundaries.

Michael
 
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.Explicit).

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top