繁体   English   中英

整理记忆<byte>到期望 byte[] 的本机函数

[英]Marshal a Memory<byte> to a native function expecting byte[]

我正在尝试用 c# 包装 OpenSSL 的 BIO 部分。 我试图将 BIO 公开为 IDuplexPipes。

BIO 有一个read(byte[] buffer, int length)函数。 如您所见,BIO 需要一个byte[]PipeWriter仅提供Memory<byte>

导入的函数如下所示:

[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public extern static int BIO_read(IntPtr b, byte[] buf, int len);

然后在 BIO 类中像这样包装:

public int Read(byte[] buffer, int length)
{
    return SSL.BIO_read(Handle, buffer, length);
}

管道的代码如下所示:

public async void DoReadAsync()
{
    var writer = _inputPipe.Writer;

    while(true)
    {
        Memory<byte> mem = writer.GetMemory(_sizeHint);

        _bio.Read(mem???, _sizeHint); <- here is my confusion.
        ...
    }
}

我希望避免将从 BIO 读取的数据复制到内存中,而是希望将Memory<bytes>的“字节数组”直接提供给BIO.read(..) 另外,我想通过writer.GetMemory()来利用MemoryPool<byte>而不是创建新的Memory<bytes> s。

我并不像我希望的那样擅长互操作,而且我在谷歌上找不到任何有用的东西。

Interop Services 提供了一种获取可以作为数组访问的 ArraySegment 的方法。

TryGetArray(ReadOnlyMemory, ArraySegment)

尝试从底层内存缓冲区中获取数组段。 返回值表示操作成功。

https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices?view=netcore-3.0

using System.Runtime.InteropServices;

//Turn memory space into ArraySegment for port use
if (!MemoryMarshal.TryGetArray(memory, out ArraySegment<byte> arraySegment))
{
    throw new InvalidOperationException("Buffer backed by array was expected");
}

int bytesRead = port.Read(arraySegment.Array, 1000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM