我正在编写自定义二进制序列化器,我希望将固定长度数据类的数组转换为byte [],反之亦然。这是一个示例数据类:
[Serializable, StructLayout(LayoutKind.Sequential)]
public class DataPoint
{
float A{ get; set; }
float B{ get; set; }
float C{ get; set; }
}
这是我尝试序列化的最佳尝试,但没有成功:
// '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);
}
那里有更好的想法吗?
谢谢,
亚伦