简体   繁体   English

我如何在struct中声明数组?

[英]How I can declare arrays in struct?

How can I declare structure with a fixed size array in it? 如何在其中声明具有固定大小数组的结构?

I found solution, but it only works for primitive data-types. 我找到了解决方案,但它只适用于原始数据类型。 I need my array to be of type MyStruct . 我需要我的数组是MyStruct类型。

So how can I declare a struct with an array of other structs in it? 那么如何在其中声明一个包含其他结构数组的结构?

ex. 恩。

    unsafe struct Struct1{
      fixed int arrayInt[100]; // works properly 
      fixed Struct2 arrayStruct[100]; //not compile
    }

My colleague found the working way to do this. 我的同事找到了这样做的工作方式。 I think it`s right way. 我认为这是正确的方式。

    [StructLayout(LayoutKind.Sequential)]
     public struct Struct1
     {
           [MarshalAs(UnmanagedType.ByValArray, SizeConst = sizeOfarray)]
           private Struct2[] arrayStruct;
     }

You can't. 你不能。 Fixed arrays are restricted to bool, byte, char, short, int, long, sbyte, ushort, uint, ulong, float, or double. 固定数组仅限于bool,byte,char,short,int,long,sbyte,ushort,uint,ulong,float或double。

See http://msdn.microsoft.com/en-us/library/zycewsya%28v=VS.80%29.aspx 请参阅http://msdn.microsoft.com/en-us/library/zycewsya%28v=VS.80%29.aspx

One approach to do your interop might be to code a wrapper assembly in C++ which does the translation to a more C#-interop-friendly structure. 执行互操作的一种方法可能是在C ++中编写一个包装程序集,它可以转换为更加C#-interop友好的结构。

You can't use custom types with fixed arrays. 您不能将自定义类型与固定数组一起使用。 (See TTonis answer for details.) (有关详细信息,请参阅TTonis答案。)

Instead of trying to construct a structure in C# with a specific memory layout, I think that you should use the MarshalAs attribute to specify how the members should be marshalled. 我认为您应该使用MarshalAs属性来指定如何编组成员,而不是尝试使用特定的内存布局在C#中构造结构。 Even if you manage to get members that occupy the right amount of memory, you still have padding between the elements that causes you alignment problems. 即使你设法让成员占用大量内存,你仍然会在元素之间填充,导致对齐问题。

You can have a reference to a regular array in the structure, and specify that it should be marshalled as ByValArray . 您可以在结构中引用常规数组,并指定它应该被编组为ByValArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM