2009-05-19 52 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