How I can declare arrays in struct?

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-12 18:46:42

问题


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.

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
    }

回答1:


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;
     }



回答2:


You can't. Fixed arrays are restricted to bool, byte, char, short, int, long, sbyte, ushort, uint, ulong, float, or double.

See 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.




回答3:


You can't use custom types with fixed arrays. (See TTonis answer for details.)

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. 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.



来源:https://stackoverflow.com/questions/4123314/how-i-can-declare-arrays-in-struct

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