Fixed Size Array of Structure type

痴心易碎 提交于 2019-12-06 21:36:10

问题


how do I declare fixed-size array of a structure type in C# :

[StructLayout(LayoutKind.Sequential,Pack=1), Serializable]
public unsafe struct MyStruct{
    ...
}

public class MyClass {
    ...
    public fixed MyStruct myStruct[256];
}

this will result to CS1663 : fixed size buffers of struct type is not allowed, how do I workaround this ?, I prefer not to use C# or "Managed Collection data structure" type, as I need to frequently marshall this to native C++


回答1:


If your C# struct uses only primitive data types and has exactly the same layout as your native struct in C++, you can get around these restrictions with manual memory management and unsafe code. As a bonus, you will improve performance by avoiding marshalling.

Allocate the memory:

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

This is basically malloc, so the allocated memory is outside the awareness of the GC.

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

To read/write the structs in the array with 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;
}

Don't forget to

Marshal.FreeHGlobal (arr);

when you're done with the memory, to free it.




回答2:


You can't; per the definition

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



来源:https://stackoverflow.com/questions/7973998/fixed-size-array-of-structure-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!