I am writing a custom binary serializer and I'd like to convert from an array of fixed length data classes to a byte[], and the reverse. Here's an example data class:
[Serializable, StructLayout(LayoutKind.Sequential)]
public class DataPoint
{
float A{ get; set; }
float B{ get; set; }
float C{ get; set; }
}
Here's my best attempt at serialization, which didn't work:
// 'value' is a pointer to DataPoint[]
public byte[] SerializeArray(object value)
{
Type type = value.GetType();
Type etype = type.GetElementType();
int esize = Marshal.SizeOf(etype);
// I was hoping this would return the array length, but it throws
int size = Marshal.SizeOf(value);
IntPtr ptr = Marshal.AllocHGlobal(esize*size);
Marshal.StructureToPtr(value, ptr, false);
byte[] bytes = new byte[esize * size];
Marshal.Copy(ptr, bytes, 0, esize * size);
Marshal.FreeHGlobal(ptr);
}
Any better ideas out there?
Thanks,
Aaron