Search code examples
c#.netunmanaged-memory

How to copy Span<byte> contents to location pointed by IntPtr?


I have an instance of Span<byte> which I would like to copy to unmanaged memory pointed by IntPtr. If I had a byte[], this would be an easy job, just call Marshal.Copy:

enter image description here

I know I can convert Span<byte> to byte[] by calling ToArray, but that would require additional allocation, which I am trying to avoid. Is there any clean, non-allocating (also not using unsafe if possible) way to copy contents of Span<byte> to unmanaged memory pointed by IntPtr?


Solution

  • Turning the IntPtr into a Span<byte> will allow copying the source span into the span representing the unmanaged buffer.

    However, a Span<T> cannot be directly derived from an IntPtr, but rather requires turning the IntPtr into a void* pointer first and then creating a Span<T> from that pointer:

    var spanUnmanagedBuffer = new Span<byte>(intPtrUnmanagedBuffer.ToPointer(), sizeUnmanagedBuffer);
    

    Creating a Span<T> this way requires unsafe context, unfortunately.