I am trying to serialize a structure to disk as raw bytes. This is a (simplified)version of it.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class TestData :BaseStructure
{
public byte[] bytes = new byte[]{65,66,67}; // this doesn't write ABC as expected
}
A write function uses ConvertStructureToBytes method to convert this to a byte array and a binary writer then writes it.
public void Write(BaseStructure baseStructure)
{
binaryWriter.Write(ConvertStructureToBytes(baseStructure));
}
The ConvertStructureToBytes section
public byte[] ConvertStructureToBytes(BaseStructure baseStructure)
{
int len = Marshal.SizeOf(baseStructure);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(baseStructure, ptr,false);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
If I replace the bytes line to
public byte byte = 65; // This now writes an A , as expected
I have tried
public byte[] bytes = Encoding.ASCII.GetBytes("ABC"); //doesn't work either
This probably has something to do with the ConvertStructureToBytes function , it isn't treating the byte array as it should.
What do I need to do to be able to write 'ABC' successfully?
BaseStructure? YourTestDataclass inherits from it, but you are not serialising aTestDatainstance but aBaseStructureinstance, which is not aware of the data declared in theTestDataclass.