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

时间:2011-11-25 11:43:11

标签: c# c++ dll marshalling unmanaged

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

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

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

2 个答案:

答案 0 :(得分: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];
    }
}

答案 1 :(得分:1)

在这种情况下,您无需使用def array123(nums): for i in range(len(nums)): if nums[i:i+3] == [1,2,3]: return True return False 。只需使用IntPtr

unsafe contexts

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