I have preallocated Span<byte> and unmanaged memory pointed by IntPtr and I want to copy contents from the Span into unmanaged memory.
I would like to avoid additional allocations and unsafe context.
The task looks pretty simple, but I found that Marshal.Copy only supports copying from byte[] and can't process Span in any way. So, with Marshal.Copy I ended up with a following code, which envolves an intermediate allocation of byte[]
Span<byte> src = GetSpan();
IntPtr dst = GetUnmanagedMemoryPointer();
byte[] tmp = src.ToArray();
Marshal.Copy(tmp, 0, dst, src.Length);
The other way I found is to wrap the unmanaged memory with the Span, but this envolves unsafe
Span<byte> src = GetSpan();
IntPtr dst = GetUnmanagedMemoryPointer();
Span<byte> dstSpan;
unsafe
{
dstSpan = new Span<byte>(dst.ToPointer(), src.Length);
}
src.CopyTo(dstSpan);
Both variants works, but both are non-perfect.
So, can we perform direct copy from Span into unmanaged memory without unsafe context and/or additional intermediate allocations?