views:

162

answers:

2

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);
A: 

In C# it makes more sense to implement ISerializable and use the BinaryFormatter class to write the struct to disk.

ISerializable

ChaosPandion
+1  A: 

Not possible because of the nested struct arrays. See When I try to use a structure containing an array of other structures, I get an exception. What's wrong?.

hjb417
This was my hunch. I was hoping it to not be the case. Thanks.
Chris