C#缓冲区的通用读/写方法

时间:2014-08-26 04:09:28

标签: c# templates generics buffer

我一直在尝试编写一个Buffer类,它允许我使用泛型方法写入和读取内部List缓冲区。在C ++中没有问题,因为我们可以直接访问内存(memcpy(我知道memcpy是不安全的)等等。)

我尝试了以下内容:

// 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));
}

......但它说,最好的重载有一些无效的参数(值)。

我在读取byte,short,ushort,int或uint类型的值时也遇到了问题。我当然可以确定T的类型,然后使用BitConverter类转换字节,但我确信有一种更简单和干燥的方法来做到这一点(我还没有发现)。

如何实现这样的方法来保持课堂的美观和简单?

修改

为了从缓冲区中读取,我尝试了以下内容:

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;
}

但它在此行中引发了一个System.ArgumentException Marshal.PtrToStructure(ptr,data);

1 个答案:

答案 0 :(得分:0)

这样的事情会满足你的需求吗?

public void Write<T>(T value) where T: struct
{
    int size = Marshal.SizeOf(value);
    var bytes = new byte[size];
    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.StructureToPtr(value, ptr, true);
    Marshal.Copy(ptr, bytes, 0, size);
    Marshal.FreeHGlobal(ptr);
    _buffer.AddRange(bytes);
}