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

cur*_*ity 2 c# c++ dll unmanaged marshalling

在c ++我有这样的功能

extern "C" _declspec(dllexport) uint8* bufferOperations(uint8* incoming, int size)
Run Code Online (Sandbox Code Playgroud)

我试图从c#这样调用它

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

但我得到了无法编组'返回值':无效的托管/非托管类型组合

((问题是 - 如何正确编组?感谢您阅读我的问题

Vla*_*lov 9

byte []是一个已知长度的.Net数组类型.你不能编组字节*,因为.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];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @curiousity.没问题,我来自莫斯科,Luxoft.我认为其他用户用英语写作更礼貌.:) (2认同)