Search code examples
asp.net-core.net-corepinvokeunsafe

c# ReadOnlyMemory from pointer


Hi there I have a c native library that is returning me json as char*. What I would like to do in c# is to use this pointer and write it straight to the

this.ControllerContext.HttpContext.Response.BodyWriter;

I'm able to create ReadOnlySpan from the ptr but as far as I can tell PipeWriter only accepts ReadOnlyMemory<byte> which does not have a constructor from IntPtr. Is there a way to create ReadOnlyMemory<byte> from IntPtr or some other way to writer my string from native library withou copying it one extra time?


Solution

  • Thank you for your answers but none of them was without extra copy. I was finally figure it out so in case somebody struggle with it, here is the solution.

    So the only way I as able to achieve this is like.

     await Response.StartAsync(HttpContext.RequestAborted);
     var dest = Response.BodyWriter.GetMemory((int)jsonLen).Pin();
     unsafe { memcpy(dest.Pointer), srcPtr, srcLen); }
     Response.BodyWriter.Advance(srcLen);
     await Response.BodyWriter.FlushAsync(HttpContext.RequestAborted);