C# 如何复制内存<;字节>;到字节[]中的特定偏移量
我正在使用异步网络IO,我的读取缓冲区在内存中,我正在尝试将内存复制到字节[]的特定偏移量C# 如何复制内存<;字节>;到字节[]中的特定偏移量,c#,C#,我正在使用异步网络IO,我的读取缓冲区在内存中,我正在尝试将内存复制到字节[]的特定偏移量 public bool Append(Memory<byte> buffer) { // Verify input data if (buffer.Length <= 0 || buffer.Length > PacketSize - Received) { // Debug.Assert(false); re
public bool Append(Memory<byte> buffer)
{
// Verify input data
if (buffer.Length <= 0 ||
buffer.Length > PacketSize - Received)
{
// Debug.Assert(false);
return false;
}
// Copy received data into packet at current offset
// TODO : Avoid heap array allocation or iteration
//Buffer.BlockCopy(buffer.ToArray(), 0, Packet, Received, buffer.Length);
//private readonly byte[] Packet;
for (int i = 0; i < buffer.Length; i ++)
{
Packet[Received + i] = buffer.Span[i];
}
Received += buffer.Length;
// If we have a header it must match
if (HasHeader() && !DoesHeaderMatch())
{
// Debug.Assert(false);
return false;
}
return true;
}
希望我能明白你的意思 所以你有一个缓冲区,一个数据包,你很乐意让它成为一个跨度。它在Hello World中有一些数据:
byte[] buf = Encoding.ASCII.GetBytes("Hello World");
var bufSpan = buf.AsSpan();
还有一些其他数据作为另一个跨度:
byte[] otherSpan = Encoding.ASCII.GetBytes("rr").AsSpan();
您希望将数据写入缓冲区中的某个位置。您必须首先对缓冲区进行切片,然后将新数据复制到切片创建的范围中
otherSpan.CopyTo(bufSpan.Slice(2)); //replace the ll with rr
Console.WriteLine(Encoding.ASCII.GetString(bufSpan.ToArray())代码>打印“Herro World”因此,您希望连接两个Span,而不使用第三个缓冲区的技术,该缓冲区已经被适当地分割了两个Span?数据包是在构造函数中分配并重新使用的字节[]。我不想创建临时对象,我想直接复制数据包[]中指定偏移量处的内存。
otherSpan.CopyTo(bufSpan.Slice(2)); //replace the ll with rr