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
Your managed function declaration would look something like this in the header file:
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:
Finally, calling it from C#:
**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.