2

Having the following function in a native dll:

double sum (std::vector<double> vals)
{
    double s = 0.0;
    for (size_t = 0; i < vals.size(); i++)
    {
        s += vals[i]
    }
    return s;
}

How can I make it callable from .net (c#) ?

The problem is, that there is no pair for vector<double>.

Is it possible to alter the c++ side to make the call possible? (without giving up any std c++ feature, including the ability to call other c++ libraries )

András Kovács
  • 847
  • 1
  • 10
  • 29

1 Answers1

1

It is not possible and should not be done: do not pass stl classes over dll interface

However you could create a c-function which could easily be called by c#. As parameters you could pass a c-array of doubles and a second parameter - the length of the array. The wrapper function could convert this to the std::vector and call the original function.

double sumWrapper(double* pointerToDoubleArray, unsigned int numberOfElements) {
    //convert and call sum
}

This c-function can be called by C++ by using custom marshalling as described here. Another option is the simple wrapper generator (swig) to auto - generate the c-wrapper function and a c# function that calls the C++ function in the dll.

The other option you have is add a C++/Cli wrapper function that can be called from C# and converts the .net array of doubles to a stl vector.

Community
  • 1
  • 1
David Feurle
  • 2,687
  • 22
  • 38