0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.