从 C# 调用 C++ dll。 "Cannot marshal 'return value': Invalid managed/unmanaged type combination."

Calling C++ dll from C#. "Cannot marshal 'return value': Invalid managed/unmanaged type combination."

我的头文件。

extern "C"  class MyFuncs
{
 public:
    __declspec(dllexport) unsigned char PassImage(unsigned char buffer, int size);
};

CPP 文件。

unsigned char MyFuncs::PassImage(unsigned char buffer, int size)
{
    return buffer;
}

除了我 return 将缓冲区返回到我的主应用程序时,一切正常。

    [DllImport("ExampleDLL.dll", EntryPoint = "?PassImage@MyFuncs@Funcs@@QAEXEH@Z")]
    public static extern byte[] PassImage(byte[] a, int count);

当我return unsigned char to byte[]时出现错误。

如果我将 byte[] 更改为 byte,我会得到一个没有错误的值。

这是准确的错误:

Cannot marshal 'return value': Invalid managed/unmanaged type combination.

如何将 unsigned char 接受回 byte[]?

在 C++ 中,你 return 一个 unsigned char,它是一个字节长。在 C# 中,您需要一个字节 array。您可能想要 return 来自 C++ 的 unsigned char *

unsigned char 应该是 unsigned char * :)

编辑: 您还需要传递数组的长度并将其作为 C# 中的字节指针处理,因为 .NET 不知道它的长度。本文描述: