简体   繁体   中英

Return array from function in c++ lib into c# programm

I need return integer values in c++ lib into c#. In c++ lib it return pointer, because I know, that in c++ we cannot return an array. I need that integer values to operate in 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;
}

The question is : what is the best way return values from c++ library into c#? What should I change?

The optimal way is to let the caller pass an array that you fill in with your C function. Like this:

int FindShortestPath(int from, int to, int[] buffer, int bufsize)

Now the C# code can simply pass an int[] as the buffer argument. Copy the vector content into it. Be sure to observe bufsize , you are copying directly into the GC heap so if you copy beyond the end of the array then you'll destroy that heap.

If bufsize is too small then return an error code, negative numbers are good. Otherwise return the actual number of copied elements. If the C# code cannot guess at the required buffer size then a convention is to first call the function with a null buffer. Return the required array size, the C# code can now allocate the array and call the function again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM