我用 C++ 创建了一个跨平台的 DLL,可以在 Windows 和 Mac OSX 上编译。在 Windows 上,我有一个 C# 应用程序使用 P/Invoke 调用 DLL,而在 Mac OSX 上,一个目标 C 应用程序调用 DLL。我的简单函数工作得很好,但我需要一个返回整数数组的新函数。
我能找到的最好的例子是Marshal C++ int array to C#,我能够让它工作。但是,我想修改此示例以将整数数组作为参考参数传回。数组的大小必须在运行时设置。
这是我尝试过的。pSize 正确返回,但列表为空。
在非托管 C++ 中:
bool GetList(__int32* list, __int32* pSize)
{
// Some dummy data
vector<int> ret;
ret.push_back(5);
ret.push_back(6);
list = (__int32*)malloc(ret.size());
for (unsigned int i = 0; i < ret.size(); i++)
{
list[i] = ret.at(i);
}
*pSize = ret.size();
return true;
}
在 C# 中:
[DllImport(@"MyDll.dll",
CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public static extern bool GetList(out IntPtr arrayPtr, out int size);
public static int[] GetList() {
IntPtr arrayValue = IntPtr.Zero;
int size = 0;
bool b = GetFrames(out arrayValue, out size);
// arrayValue is 0 here
int[] result = new int[size];
Marshal.Copy(arrayValue, result, 0, size);
return result;
}