1

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

astibich
  • 71
  • 1
  • 3
  • See http://stackoverflow.com/questions/3278827/how-to-convert-a-structure-to-a-byte-array-in-c – Peter Winton Jan 15 '16 at 02:44
  • This appears to be a post about how to marshal a single fixed length data structure - although I might have missed something. I would like to marshal an array of structures without iterating (which is very slow). This is trivial in C++. You just allocate the memory and then copy the whole thing with one memcpy call. What's the equivalent in C#? – astibich Jan 15 '16 at 15:32
  • Ah, I misunderstood. Have you tried making DataPoint a struct instead of a class? I believe an array of _objects_ (declared via "class") is laid out in memory as an array of references, whereas an array of _values_ (declared via "struct") would have the actual data laid out sequentially as in C++. See https://msdn.microsoft.com/en-us/library/ms173109.aspx – Peter Winton Jan 15 '16 at 18:24

0 Answers0