问题描述
我如何申报在C#中的结构类型的固定大小的数组:
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];
}
这将导致到CS1663:?结构类型的固定大小的缓冲区是不允许的,我怎么解决这个,我preFER不使用C#或托管集合数据结构式的,因为我需要经常马歇尔这对本地C ++
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++
推荐答案
如果你的C#结构只使用基本的数据类型,并具有完全相同的布局在C ++中本机结构相同,让您可以与手动内存管理,这些限制不安全code。作为奖励,你将避免编组来提高性能。
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.
分配内存:
IntPtr arr = Marshal.AllocHGlobal (sizeof (MyStruct) * 256);
这是基本的malloc
,所以分配的内存是GC的意识之外。
This is basically malloc
, so the allocated memory is outside the awareness of the GC.
您可以通过IntPtr的天然code,好像它是一个 MYSTRUCT [256]
,只有IntPtr的将被整理,而不是它所指向的内存。本机和托管code可以直接访问相同的内存。
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.
要读/写的结构与C#中的数组中,使用C#指针:
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;
}
不要忘了
Marshal.FreeHGlobal (arr);
当你与内存中完成,以免费
了。
这篇关于结构类型的固定大小数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!