How I can declare arrays in struct?

早过忘川 提交于 2019-12-04 05:08:43

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.

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.

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.

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