Recently, I came across a situation where I need to create a general method for reading a data type from a byte array.
I created the following class:
public class DataStream { public int Offset { get; set; } public byte[] Data { get; set; } public T Read<T>() where T : struct { unsafe { int dataLen = Marshal.SizeOf( typeof( T ) ); IntPtr dataBlock = Marshal.AllocHGlobal( dataLen ); Marshal.Copy( Data, Offset, dataBlock, dataLen ); T type = *( ( T* )dataBlock.ToPointer() ); Marshal.FreeHGlobal( dataBlock ); Offset += dataLen; return type; } } }
Now, if the problems with the allocated allocation aside, this code does not compile with this message:
Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
Which seems odd because you should be able to perform the above operations based on where T : struct constraint on the method.
If this code is terribly incorrect, is there an easy way to take a series of bytes and type them into type ' T ?
Thanks!
source share