Good afternoon, I can not understand why when using Marshal.SizeOf() for a type where there is a variable array, the function returns other values. For example, I have a structure on my hands:

 struct MyStruct { public int[] Value; } 

When using Marshal.SizeOf(typeof(MyStruct)) 4, as I understand it, the size of the array type is taken, that is, int (4 bytes, that's right). But if I write something like this:

 MyStruct myStruct = new MyStruct() { Value = new int[] { 1, 2 } }; Marshal.SizeOf(myStruct); 

Obviously, the result should be 8, but it gives 4. Is there a way to declare an array of a certain length in the structure so that Marshal.SizeOf correct results?

  • one
    in the second case, you look at the pointer size. But he doesn’t care what is inside the structure or array. - KoVadim 7:43 pm

1 answer 1

int[] is a reference type, it is stored as a reference, and not “embedded” in the original type. So you get the size of the link (not the size of int )

Marshal.SizeOf gave the correct result.


If you really want to keep your buffer inside the structure, you will have to resort to unsafe code and arrays of fixed size :

 [StructLayout(LayoutKind.Explicit)] unsafe struct MyStruct { [FieldOffset(0)] public fixed int Value[2]; } 

For such a structure, Marshal.SizeOf<MyStruct>() will Marshal.SizeOf<MyStruct>() desired 8.

Do not forget to mark in the properties of the project Build → General → Allow unsafe code. But this should be done only for the case of a tricky interop, in normal cases, avoid such code.


Update:

If you really do not care how exactly the memory allocation in managed code looks like, and you only need to properly marshall to native code, you will need an explicit indication of the marshalling method:

 public struct MyStruct { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public int[] Value; } 

Additional reading on the topic: Working with structures in C # .

  • Yes, a clear indication of the size will do, thanks! - Mark Khromov
  • @MarkKhromov: Please! But still, look towards the custom marshalling version. - VladD