Asp.net core c从指针读取内存

Asp.net core c从指针读取内存,asp.net-core,.net-core,pinvoke,unsafe,Asp.net Core,.net Core,Pinvoke,Unsafe,您好,我有一个c本机库,它将json作为char*返回给我。我想在c中做的是使用这个指针并直接将它写入 this.ControllerContext.HttpContext.Response.BodyWriter; 我可以从ptr创建ReadOnlySpan,但据我所知,PipeWriter只接受ReadOnlyMemory,它没有来自IntPtr的构造函数。有没有一种方法可以从IntPtr创建ReadOnlyMemory,或者通过其他方法从本机库编写字符串,而无需再复制一次?也许可以使用类似

您好,我有一个c本机库,它将json作为char*返回给我。我想在c中做的是使用这个指针并直接将它写入

this.ControllerContext.HttpContext.Response.BodyWriter;

我可以从ptr创建ReadOnlySpan,但据我所知,PipeWriter只接受ReadOnlyMemory,它没有来自IntPtr的构造函数。有没有一种方法可以从IntPtr创建ReadOnlyMemory,或者通过其他方法从本机库编写字符串,而无需再复制一次?

也许可以使用类似的方法

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

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

如果这可以加快速度并与您想要的匹配,我很高兴

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

谢谢你的回答,但没有一个答案没有多余的副本。我终于想出来了,所以万一有人和它斗争,这里是解决办法

所以我能做到这一点的唯一方法是

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

您好,非常感谢您的回答,但是PtrToStringAnsi实际上复制了字符串,所以我不需要:/you's welcome。它不是复制字符串,而是将c字符串char*转换为c字符串对象。但如果不需要c字符串,则必须从指针偏移量为每个字节数据生成序列化。您希望字符串有多大?过早优化是万恶之源……这看起来真的像是在复制。这是一个不安全的副本,我想它可能会更快,但它不是没有副本的。第3行的代码似乎是坏的。