c# - 从 C++ 库中的函数返回数组到 C# 程序

标签 c# c++ dll function-pointers

我需要将 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/

相关文章:

c# - 读取 "Large"文件时内存不足异常

c# - 去掉所有 HTML 标签和格式 (RegEx)

c# - 如何为listBox中的项目着色为不同的颜色?出现异常 : Items collection cannot be modified when the DataSource property is set

javascript - 从前端javascript中加载的DLL调用函数(在客户端javascript中加载dll)

java - Power BI 嵌入式 : Get Report details API responds with 400 Bad request

c++ - 如果手册中未提及,如何查找 PinPad XFS 的逻辑名称

c++ - 预处理器和模板参数或代码段的条件编译

c++ - 为什么我不能将此运算符重载放在与结构相同的 namespace 中?

C# 在调用耗费大量内存的 native 代码 DLL (Delphi) 后内存不足

c# - 结合 C# 和 C 的优点/缺点