Return 从 C++ 库中的函数到 C# 程序的数组
Return array from function in c++ lib into c# programm
我需要 return 将 c++ 库中的整数值转换为 c#。
在 c++ lib 中它是 return 指针,因为我知道,在 c++ 中我们不能 return 数组。我需要整数值才能在 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;
}
问题是:return 值从 c++ 库到 c# 的最佳方法是什么?
我应该改变什么?
最佳方法是让调用者传递一个数组,您用 C 函数填充该数组。像这样:
int FindShortestPath(int from, int to, int[] buffer, int bufsize)
现在 C# 代码可以简单地传递一个 int[] 作为 buffer 参数。将矢量内容复制到其中。请务必观察 bufsize,您正在直接复制到 GC 堆中,因此如果您复制超出数组末尾,则会破坏该堆。
如果bufsize太小那么return一个错误代码,负数是好的。否则 return 复制元素的实际数量。如果 C# 代码无法猜测所需的缓冲区大小,则惯例是首先使用 null 缓冲区调用该函数。 Return 所需的数组大小,C# 代码现在可以分配数组并再次调用函数。
我需要 return 将 c++ 库中的整数值转换为 c#。 在 c++ lib 中它是 return 指针,因为我知道,在 c++ 中我们不能 return 数组。我需要整数值才能在 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;
}
问题是:return 值从 c++ 库到 c# 的最佳方法是什么? 我应该改变什么?
最佳方法是让调用者传递一个数组,您用 C 函数填充该数组。像这样:
int FindShortestPath(int from, int to, int[] buffer, int bufsize)
现在 C# 代码可以简单地传递一个 int[] 作为 buffer 参数。将矢量内容复制到其中。请务必观察 bufsize,您正在直接复制到 GC 堆中,因此如果您复制超出数组末尾,则会破坏该堆。
如果bufsize太小那么return一个错误代码,负数是好的。否则 return 复制元素的实际数量。如果 C# 代码无法猜测所需的缓冲区大小,则惯例是首先使用 null 缓冲区调用该函数。 Return 所需的数组大小,C# 代码现在可以分配数组并再次调用函数。