Search code examples
c#marshallingbinaryformatterbinary-serialization

difference of two methods for converting byte[] to structure in c#


I'm doing some conversions between some structures and thier byte[] representation. I found two way to do this but the difference (performance, memory and ...) is not clear to me.

Method 1:

public static T ByteArrayToStructure<T>(byte[] buffer)
{    
    int length = buffer.Length;
    IntPtr i = Marshal.AllocHGlobal(length);
    Marshal.Copy(buffer, 0, i, length);
    T result = (T)Marshal.PtrToStructure(i, typeof(T));
    Marshal.FreeHGlobal(i);
    return result;
}

Method 2:

public static T Deserialize<T>(byte[] buffer)
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer))
    {
        return (T)formatter.Deserialize(stream);
    }
}

so which one is better and what is the major difference?


Solution

  • When using the BinaryFormatter to Serialize your data, it will append meta data in the output stream for use during Deserialization. So for the two examples you have, youll find it wont produce the same T output given the same byte[] input. So youll need to decide if you care about the meta data in the binary output or not. If you dont care, method 2 is obviously cleaner. If you need it to be straight binary, then you'll have to use something like method 1.