c#ReadOnlyMemory from Pointer

问题描述 投票:0回答:3

[嗨,我有一个c本机库,正在将我的json作为char *返回。我想在c#中做的是使用此指针并将其直接写到

this.ControllerContext.HttpContext.Response.BodyWriter;

我能够从ptr创建ReadOnlySpan,但据我所知,PipeWriter仅接受ReadOnlyMemory<byte>,该C0没有IntPtr的构造函数。有没有一种方法可以从IntPtr创建ReadOnlyMemory<byte>,还是可以通过其他方式从本地库写入我的字符串,而无需额外复制一次?]

asp.net-core .net-core pinvoke unsafe
3个回答
0
投票
public class Utility { public System.ReadOnlyMemory<T> ConvertToReadOnlyMemory(System.ReadOnlySpan<T> input) { var tmp = new System.Memory<T>(); input.CopyTo(tmp.Span); return (System.ReadOnlyMemory<T>)tmp; } }

但是,我认为这将涉及将流完全复制到堆存储中,这可能不是您想要的...


0
投票
namespace Helper { using System; using System.Runtime.InteropServices; public static class CStringMapper { // convert unmanaged c string to managed c# string public string toCSharpString(char* unmanaged_c_string) { return Marshal.PtrToStringAnsi((IntPtr)unmanaged_c_string); } // Free unmanaged c pointer public void free(char* unmanaged_c_string) { Marshal.FreeHGlobal((IntPtr)unmanaged_c_string); } } }

用法:

 using Helper;

 /* generate your unmanaged c string here */

 try
 {
     // eg. char* OO7c = cLibFunc();
     string cSharpString = CStringMapper.toCSharpString(OO7c);
 } 
 finally
 {
     // Make sure to  freeing the pointer
     CStringMapper.free(OO7c);
 }

0
投票
所以我唯一能够实现这一目标的方法就是。

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

© www.soinside.com 2019 - 2024. All rights reserved.