I have to create an instance of an arbitrary value type from the bytes stored at some given offset in an array of bytes (for example, if type is int
, 4 bytes shall be taken). I know I can easily do it using pointers to fixed objects, but I don't want to have unsafe
code. So I try the following code (sanity checks were stripped):
public object GetValueByType(System.Type type, byte[] byteArray, int offset)
{
int size = System.Runtime.InteropServices.Marshal.SizeOf(type);
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(byteArray, offset, size);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
BinaryFormatter binaryFormatter = new BinaryFormatter();
object obj = (object)binaryFormatter.Deserialize(memoryStream);
return obj;
}
But this code breaks at binaryFormatter.Deserialize
.
How may I fix the above code (or achieve the same purpose in any other way)?