从c#中的非托管c++ DLL中获取字节数组上的指针

本文关键字:字节数 字节 数组 获取 指针 c++ DLL | 更新日期: 2023-09-27 18:15:37

在c++中我有这样的函数

extern "C" _declspec(dllexport) uint8* bufferOperations(uint8* incoming, int size)

我正在尝试从c#中调用它,像这样

[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
//[return: MarshalAs(UnmanagedType.ByValArray)]//, ArraySubType=UnmanagedType.SysUInt)]
public static extern byte[] bufferOperations(byte[] incoming, int size);

但是我得到了无法封送"返回值":无效的托管/非托管类型组合

(()问题是-如何正确地编组它?谢谢你阅读我的问题

从c#中的非托管c++ DLL中获取字节数组上的指针

byte[]是一个已知长度的。net数组类型。你不能封送byte*给它,因为。net不知道输出数组的长度。您应该尝试手动编组。将byte[]替换为byte*。然后,像这样做:

[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern byte* bufferOperations(byte* incoming, int size);
public void TestMethod()
{
    var incoming = new byte[100];
    fixed (byte* inBuf = incoming)
    {
        byte* outBuf = bufferOperations(inBuf, incoming.Length);
        // Assume, that the same buffer is returned, only with data changed.
        // Or by any other means, get the real lenght of output buffer (e.g. from library docs, etc).
        for (int i = 0; i < incoming.Length; i++)
            incoming[i] = outBuf[i];
    }
}

在这种情况下不需要使用unsafe contexts。只要使用IntPtr。

[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr bufferOperations(IntPtr incoming, int size);

然后你可以使用Marshal。复制以从中获取字节数组