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 a C ++ managed module.

 var discountedPrices = MyManagedCpp.GetDiscountedPrices(prices) ; 

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

Edit: I managed to assemble it. My C # code:

  [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 is:

  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 get a runtime error:

System.InvalidCastException: The specified listing is not valid.

Edit: The Kevin solution is working. I also found a useful link: C ++ / CLI Keywords: under the hood

+4
source share
2 answers

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

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

Here is an example of the implementation of the above function, which simply subtracts the hard-set 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 }); 

** Please note that if your C ++ managed function passes an array to its own function, it will have to march data to prevent garbage collection. It is hard to show a concrete example without knowing what your native function looks like, but you can find some good examples here .

+4
source

Since you are in managed C ++, I believe that you want the GetDiscountedPrices signature GetDiscountedPrices be:

 array<double>^ GetDiscountedPrices(array<double>^ prices); 
+1
source

All Articles