繁体   English   中英

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

[英]get pointer on byte array from unmanaged c++ dll in c#

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

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

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

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

在这种情况unsafe contexts ,您不需要使用unsafe contexts 只需使用IntPtr

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

然后你可以使用Marshal.Copy从中获取你的字节数组。

暂无
暂无

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

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