1

Please, can anyone tell what is the size of the structure, and how to calculate it:

[StructLayoutAttribute(LayoutKind.Sequential, Pack=2)]
public struct SomeStruct
{
     public short sh;
     public int   i;
     public byte  b;
     public ushort u;
     [MarshalAs(UnmanagedType.ByValArray, SizeConst=7)]
     public byte[] arr;
}
user3101007
  • 691
  • 2
  • 7
  • 18

3 Answers3

3

I suppose you want to understand how is memory allocated, otherwise you can use:

System.Runtime.InteropServices.Marshal.SizeOf(TheStruct)

Well you choose to pack in a 2 byte boundary, so you basically allocate memory at step of two. so short ( signed or unsigned ) take 2 bytes, int take four bytes byte would take just one, but due to the packing you specify take two as well, for the same reason for the array we need to consider 8. So we have

2+4+2+2+8 = 18 bytes
Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
1

You can get exact size of this structure using following code -

System.Runtime.InteropServices.Marshal.SizeOf(SomeStruct)
Bhalchandra K
  • 2,631
  • 3
  • 31
  • 43
0

Try this:

int size = System.Runtime.InteropServices.Marshal.SizeOf(new SomeStruct());
Console.WriteLine(size);

or, from a related post, this:

int size;
unsafe
{
    size = sizeof(SomeStruct);
}

Both will yield 18, as Felice Pollano has explained.

Community
  • 1
  • 1
Igor Ševo
  • 5,459
  • 3
  • 35
  • 80