2009-05-19 51 views
1

爲了嘗試在託管的.dll中包裝一些非託管代碼,我試圖將數據點的Generic::List轉換爲std::vector。下面是我想要做的一個片段:如何通過引用傳遞Generic :: List?

namespace ManagedDLL 
{ 
    public ref class CppClass 
    { 
     void ListToStdVec(const List<double>& input_list, std::vector<double>& output_vector) 
     { 
      // Copy the contents of the input list into the vector 
      // ... 
     } 

     void ProcessData(List<double> sampleData) 
     { 
      std::vector<double> myVec; 

      ListToStdVec(sampleData, myVec); 

      // Now call the unmanaged code with the new vector 
      // ... 
     } 
    } 
} 

編譯這給了我:

錯誤C3699:「&」:對類型不能用這種間接「常量系統::類別: :通用::名單」

我可能錯過這裏一些基本的東西(我是比較新的做事.NET的方式),但看起來合理合法的代碼給我..?

[編輯]我已經試過了安迪和達里奧的建議,他們的工作,但我該如何訪問輸入列表的成員?我已經試過各種dreferencing並沒有什麼的組合看起來編譯:

void ListToStdVec(const List<double>% input_list, std::vector<double>& output_vector) 
{ 
    int num_of_elements = input_list->Count; 
} 

void ListToStdVec(const List<double>^ input_list, std::vector<double>& output_vector) 
{ 
    int num_of_elements = input_list.Count; 
} 

...既給我:

錯誤C2662:「系統::收藏集::一般::名單:: Count :: get':無法將'this'指針從'const System :: Collections :: Generic :: List'轉換爲'System :: Collections :: Generic :: List%'

.. .so如何訪問參考/指針?

回答

1

由於List<T>是一個託管的.NET類,它由託管的GC-Handle傳遞,用^表示,而不是由C++引用。

例:

void ListToVec(List<double>^ input_list, std::vector<double>& out) 

你不需要額外const這裏。符號List<T>^%創建一個跟蹤參考(與C++指針類似),而不是通過引用調用。 只需通過list->...list[...]訪問會員。

+0

刪除const確實允許我訪問input_list的成員,但我喜歡在任何可能的情況下使輸入爲const,因爲它經常在編譯時捕獲錯誤。 – 2009-05-20 09:21:32

2

根據Herb Sutter,%是託管對象通過引用字符傳遞。代碼轉換爲以下內容,它應該工作:

void ListToStdVec(const List<double>% input_list, std::vector<double>& output_vector 
{ 
    // Copy the contents of the input list into the vector 
    // ... 
} 

編輯:我認爲const是造成問題,但我不知道爲什麼。如果您將List參數更改爲const,則第一個函數將編譯,如果您使用->運算符,而第二個函數將編譯,如果您使用.運算符(我不知道爲什麼這種差異存在 - 它沒有'沒有多大意義)。

也就是說,如果您要做的只是將List中的元素複製到vector,那麼您確實想要使用^。把它看作是對被管理對象的引用。我認爲%將用於如果你想通過參考「引用」(即參考)。將input_list重新分配給ListToStdVec()中的其他內容,並讓調用者查看該分配的結果。但是,鑑於您在使用%時使用.運營商訪問會員,這告訴我可能根本不瞭解其目的。

+0

%的行爲更像一個指針,而不像參考文獻! – Dario 2009-05-20 08:55:54