I've been trying to write a Buffer class that lets me write to and read from an internal List buffer using generic methods. In C++ it was no problem, since we have nice access to the memory directly (memcpy (I know memcpy is unsafe) and so on).
I have tried the following:
// private readonly List<byte> _buffer = new List<byte>();
public void Write<T>(T value) where T : byte, short, ushort, int, uint {
_buffer.AddRange(BitConverter.GetBytes(value));
}
... But it says, that the best overload has some invalid arguments (value).
I also have problems reading a value of the type byte, short, ushort, int or uint. I could surely determine the type of T and then use the BitConverter class to convert the bytes but i'm sure there is a more easy and DRY way to do this (which I haven't discovered yet).
How to implement such methods to keep the class sweet and simple?
EDIT:
To read from the buffer I've tried the following:
public T Read<T>(bool moveIndex = true) {
T data = default(T);
var size = Marshal.SizeOf(data);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.PtrToStructure(ptr, data);
Marshal.Copy(_buffer.ToArray(), _readIndex, ptr, size);
Marshal.FreeHGlobal(ptr);
if (moveIndex) {
_readIndex += size;
}
return data;
}
But it throws me a System.ArgumentException in this line Marshal.PtrToStructure(ptr, data);