Array of fixed size structure type

how to declare an array of fixed size structure type in C #:

[StructLayout(LayoutKind.Sequential,Pack=1), Serializable] public unsafe struct MyStruct{ ... } public class MyClass { ... public fixed MyStruct myStruct[256]; } 

this will lead to CS1663: fixed size buffers of type struct are not allowed, how can I do this? I prefer not to use the C # structure type or the "Managed Data Collection" type, since I need to march this often in native C ++

+8
arrays c # struct marshalling unsafe
source share
2 answers

If your C # structure uses only primitive data types and has exactly the same format as your own C ++ structure, you can get around these limitations with manual memory management and unsafe code. As a bonus, you will improve performance by avoiding sorting.

Allocate memory:

 IntPtr arr = Marshal.AllocHGlobal (sizeof (MyStruct) * 256); 

This is basically malloc , so the allocated memory is beyond the grasp of the GC.

You can pass IntPtr to your own code as if it were MyStruct[256] , and only IntPtr will be sorted, not the memory that it points to. Native and managed code can directly access the same memory.

To read / write structures in an array using C #, use C # pointers:

 static unsafe MyStruct GetMyStructAtIndex (IntPtr arr, int index) { MyStruct *ptr = ((MyStruct *)arr) + index; return *ptr; } static unsafe void SetMyStructAtIndex (IntPtr arr, int index, MyStruct value) { MyStruct *ptr = ((MyStruct *)arr) + index; *ptr = value; } 

Do not forget

 Marshal.FreeHGlobal (arr); 

when you are done with memory, up to free .

+9
source share

You can not; in the definition

The only limitation is that the array type must be bool , byte , char , short , int , long , sbyte , ushort , uint , ulong , float or double.

+3
source share

All Articles