我需要将 C++ 库中的整数值返回到 C# 中。 在 C++ lib 中它返回指针,因为我知道,在 C++ 中我们不能返回数组。我需要整数值才能在 C# 中运行
__declspec(dllexport) int* FindShortestPath(int from, int to)
{
//some algorithm...
return showShortestPathTo(used, p, to);
}
static int* showShortestPathTo(vector<bool> used, vector<int> p, int vertex)
{
vector<int> path;
//push to vector values
int* return_array = new int[path.size()];
//initialize array dynamically.....
return return_array;
}
问题是:从 C++ 库返回值到 C# 的最佳方式是什么? 我应该改变什么?
最佳答案
最佳方法是让调用者传递一个您用 C 函数填充的数组。像这样:
int FindShortestPath(int from, int to, int[] buffer, int bufsize)
现在 C# 代码可以简单地传递一个 int[] 作为 buffer 参数。将 vector 内容复制到其中。请务必观察 bufsize,您正在直接复制到 GC 堆中,因此如果您复制到数组末尾之外,则会破坏该堆。
如果 bufsize 太小则返回错误代码,负数是好的。否则返回复制元素的实际数量。如果 C# 代码无法猜测所需的缓冲区大小,则惯例是首先使用 null 缓冲区调用该函数。返回所需的数组大小,C# 代码现在可以分配数组并再次调用函数。
关于c# - 从 C++ 库中的函数返回数组到 C# 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36527422/