2011-07-26 20 views
4

在我的C#代碼,我有以下陣列:如何從C#雙陣列發送到C++

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

我需要把它作爲參數傳遞給我的託管C++模塊。

var discountedPrices = MyManagedCpp.GetDiscountedPrices(prices) ; 

GetDiscountedPrices的簽名怎麼樣?在最微不足道的情況下,當折扣價格等於價格時,C++方法GetDiscountedPrices應該如何?

編輯:我設法讓它編譯。我的C#代碼是這樣的:

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

我的C++代碼編譯:

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

但是我得到一個運行時錯誤:

System.InvalidCastException:指定的轉換無效。

編輯:凱文的解決方案工作。我還發現了一個有用的鏈接:C++/CLI keywords: Under the hood

+0

爲什麼'^'在'double ^'中?很顯然,你不能把'double ^'轉換成'double'。爲什麼要這麼做? – RocketR

+0

這是C++/CLI,而不是「託管C++」。 –

回答

4

你的管理函數的聲明看起來像這樣在頭文件:

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

下面是一個示例實現上述功能的,簡單地減去從輸入陣列中的每個價格的硬編碼值,並返回結果在一個單獨的陣列:

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; 
} 

最後,從C#調用它:

using SomeNamespace; 

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

**請注意,如果您的託管C++函數傳遞數組到本機的功能,它需要馬歇爾的數據,以防止垃圾收集器從觸摸它。在不知道你的本地函數是什麼樣子的情況下很難展示一個具體的例子,但你可以找到一些很好的例子here

+0

這工作,謝謝! –

1

既然你在託管C++的時候,我相信你想要的GetDiscountedPrices簽名是:

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

這不能編譯:不能在沒有頂層的情況下使用此類型'^' –

+0

簽名應該使用'array ^',注意克拉。也應該是'雙':) – porges