I have a sequential struct that I'd like to serialize to a file, which seems trivial. However, this struct consists of, among other things, 2 arrays of other types of structs. The main struct is defined as follows...
[StructLayout(LayoutKind.Sequential)]
public struct ParentStruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public const string prefix = "PRE";
public Int32 someInteger;
public DataLocater[] locater; //DataLocater is another struct
public Body[] body; //Body is another struct
};
I can create these structs exactly as intended. However, when trying to serialize with the following method (which seems popular online), I get an AccessViolationException:
public static byte[] RawSerialize(object structure)
{
int size = Marshal.SizeOf(structure);
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structure, buffer, true);
byte[] data = new byte[size];
Marshal.Copy(buffer, data, 0, size);
Marshal.FreeHGlobal(buffer);
return data;
}
I'm assuming this is because the structures don't define exactly how large the arrays are, so it cannot explicitly determine the size beforehand? It seems that since it cannot get that, it is not allocating the right amount of space for the structure and it ends up being too short when casting the structure to a pointer. I'm not sure on this. Why might this occur and what are possible alternatives?
Edit: The line throwing the error is
Marshal.StructureToPtr(structure, buffer, true);