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 .
Mikayla hutchinson
source share