[英]Return array from function in c++ lib into c# programm
我需要將c ++ lib中的整數值返回到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 []作為緩沖區參數傳遞。 將矢量內容復制到其中。 請務必注意bufsize ,您將直接復制到GC堆中,因此,如果復制超出數組末尾,則將破壞該堆。
如果bufsize太小,則返回錯誤代碼,負數是好的。 否則,返回復制元素的實際數量。 如果C#代碼無法猜測所需的緩沖區大小,則慣例是首先使用空緩沖區調用該函數。 返回所需的數組大小,C#代碼現在可以分配數組並再次調用該函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.