Arne Lund
Arne Lund

Reputation: 2446

How to send a double array from C# to C++

In my C# code, I have the following array:

var prices = new[] {1.1, 1.2, 1.3, 4, 5,};

I need to pass it as a parameter to my managed C++ module.

var discountedPrices = MyManagedCpp.GetDiscountedPrices(prices) ;

How should the signature of GetDiscountedPrices look like? In the most trivial case, when discounted prices are equal to prices, how should the C++ method GetDiscountedPrices look like?

Edit: I managed to get it to compile. My C# code is this:

    [Test]
    public void test3()
    {
        var prices = new ValueType[] {1.1, 1.2, 1.3, 4, 5,};
        var t = new TestArray2(prices , 5);
    }

My C++ code builds:

        TestArray2(     
        array<double^>^ prices,int maxNumDays)
    { 
        for(int i=0;i<maxNumDays;i++)
        {
// blows up at the line below
            double price = double(prices[i]);
        }

However I am getting a runtime error:

System.InvalidCastException : Specified cast is not valid.

Edit: Kevin's solution worked. I also found a useful link:C++/CLI keywords: Under the hood

Upvotes: 4

Views: 2876

Answers (2)

Paul Sonier
Paul Sonier

Reputation: 39480

Since you're in managed C++, I believe you want the signature of GetDiscountedPrices to be:

array<double>^ GetDiscountedPrices(array<double>^ prices);

Upvotes: 1

Kevin D.
Kevin D.

Reputation: 911

Your managed function declaration would look something like this in the header file:

namespace SomeNamespace {
    public ref class ManagedClass {
        public:
        array<double>^ GetDiscountedPrices(array<double>^ prices);
    };
}

Here's an example implementation of the above function that simply subtracts a hard-coded value from each price in the input array and returns the result in a separate array:

using namespace SomeNamespace;

array<double>^ ManagedClass::GetDiscountedPrices(array<double>^ prices) {

    array<double>^ discountedPrices = gcnew array<double>(prices->Length);
    for(int i = 0; i < prices->Length; ++i) {
        discountedPrices[i] = prices[i] - 1.1;
    }
    return discountedPrices;
}

Finally, calling it from C#:

using SomeNamespace;

ManagedClass m = new ManagedClass();
double[] d = m.GetDiscountedPrices(new double[] { 1.3, 2.4, 3.5 });

**Note that if your Managed C++ function is passing the array to a native function, it will need to marshall the data to prevent the garbage collector from touching it. It's hard to show a specific example without knowing what your native function looks like, but you can find some good examples here.

Upvotes: 4

Related Questions