Search code examples
c#c++vectormanaged-c++

Call a vector in managed C++ from C#


I want to have a vector that has a number of independent variables. In my C++ header(.h) I defined it like this:

private:
    // Static data structure holding independent variables
    static vector<double>* indVariables;

And in my .cpp file it is defined the same and then I'm going to have to use this vector in some other function like this:

static vector<double>* indVariables;

void fun(int m, int n)
{
    for (i = 0; i < m; ++i)
    {
        ai = indVariables[i];

        temp = exp(-n * (ai - 8.0));
    }
} /* fun */

Now in C# I want to copy a set of numbers to this vector and call it back to C++ something like this:

var matu = new double[]{ 8.0, 8.0, 10.0, 10.0, 10.0, 10.0};
myCppClass.indVariables = matu;

How can I do it?

The first problem is because it is private I don't see it in C#. Do I have to make it public or are there other ways? And then how can I assign values to this vector?


Solution

  • The fact that it is private does present an issue, but, making it public won't just solve your problem I think. C# doesn't know what an std::vector is, as Richard said. I don't know much about the structure of your code, what its doing, how its being used, etc, but, if all you need is to assign a list/array of numbers to the vector, you could use a List<> in your C# code and wrap the assignment of the vector in something like this in your CLI project/file:

    void Assign(Collections::Generic::List<double>^ l )
    {
        IndVariables->clear();
        for each (double i in l)
        {  
            IndVariables->push_back(i);
        }
    }
    

    Then in your C# program, you'd write (or however you've declared your List<>):

    yourCppClass.Assign(new List<double>(){0.0, 42.0, 8.0});

    You could also add additional wrapper methods to manipulate or access the vector. Again, this may or may not be suitable depending on the structure of your code.