gpt4 book ai didi

c# - 从跨平台 DLL 返回整数数组

转载 作者:太空宇宙 更新时间:2023-11-03 20:30:48 25 4
gpt4 key购买 nike

我用 C++ 创建了一个跨平台 DLL,它可以在 Windows 和 Mac OSX 上编译。在 Windows 上,我有一个使用 P/Invoke 调用 DLL 的 C# 应用程序,在 Mac OSX 上,一个 Objective-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;
}

最佳答案

“调用者分配”是使代码可移植同时保持其可维护性的唯一方法。您的代码不仅不会更改调用者的指针,而且 C# 代码也无法释放您分配的内存(malloc-ed 内存不会被垃圾回收清除)。

如果快速找到大小(不需要生成所有输出数据),只需添加第二个函数来返回大小。

如果在生成数据之前无法获取大小,则让一个函数返回大小和指向内容的指针(int**,在 C# 端它将是 ref IntPtr)。第二个函数将该数据复制到 C# 数组并释放 native 缓冲区。

关于c# - 从跨平台 DLL 返回整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7679522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com