How can I declare arrays in a structure?

How can I declare a structure with a fixed-size array?

I found a solution, but it only works for primitive data types. I need my array of type MyStruct .

So, how can I declare a structure with an array of other structures in it?

ex.

  unsafe struct Struct1{ fixed int arrayInt[100]; // works properly fixed Struct2 arrayStruct[100]; //not compile } 
+7
c # interop
source share
3 answers

My colleague found a working way to do this. I think this is the right way.

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

You can not. Fixed arrays are limited 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 doing your interaction might be to code the wrapper assembly in C ++, which makes the translation more convenient for C #.

+5
source share

You cannot use custom types with fixed arrays. (For more information, see TTon Response.)

Instead of trying to build a structure in C # with a specific memory layout, I think you should use the MarshalAs attribute to indicate how members should be ordered. Even if you manage to get members that take up the right amount of memory, you still have padding between the elements that cause alignment problems.

You can have a reference to a regular array in the structure and indicate that it should be mapped as ByValArray .

0
source share

All Articles