There have been variants on this question, but the ones I found were "I have a struct in a C DLL". In this case, I have 100% C# code. I have a struct that contains a variable length array of structs that I am trying to marshal to a tightly packed byte array. I'm using structs and Marshal.StructureToPtr because I need a tightly packed array without all of the metadata that BinaryReader/Writer use to help it serialize and deserialize.
Here is the struct definition:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CharacterSelect_Struct
{
public uint CharCount;
public uint TotalChars;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct)]
public CharacterSelectEntry_Struct[] Entries;
public static CharacterSelect_Struct Initialize(uint totalChars, uint charCount)
{
return new CharacterSelect_Struct
{
CharCount = charCount,
TotalChars = totalChars,
Entries = 0 != charCount ? new CharacterSelectEntry_Struct[charCount] : null
};
}
}
This works great if Entries contains 1 element. If it contains 2 or more I still only ever get the contents of the first element.
Is there a way to serialize the above and get all of the contents of Entries, or do I have to manually serialize the above, and if so, other than doing, "Serialize each Entry separately and append to a list, then serialize the outer struct"?
I went with a struct and Marshal.StructureToPtr approach because it seemed easier than going with classes and manually writing all of the serialization and deserialization using BitConverter, but I'm wondering if there's a simpler way to give me what I need..