开发者

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.

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 arraySt开发者_运维问答ruct[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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜