Skip to main content
 首页 » 编程设计

c#之将 STL/C++/CLI 容器传递给 .Net

2024年02月05日8kerrycode

我有一个向量 cv::Point2f。我想要的是将此向量从 C++/CLI 传递给 C#。

因为我不能只将 cv::Point2f 存储到 std::vector 中,所以我使用了 cliext::vector。 然后,我不确定如何从 C# 中获取它...

这是我的 C++/CLI 代码:

points 是已在其他地方定义和初始化的 cv::Point2f 向量。

在 C++/CLI 中,

cliext::vector<System::Drawing::Point> ManagedCPP::Points::get() { 
    cliext::vector<System::Drawing::Point> cliext_points; 
 
    for (auto &point : points) { 
      cliext_points.push_back(System::Drawing::Point(points.x, points.y)); 
    } 
    return corners; 
} 

在 C# 中,

ManagedCPP mcpp = new ManagedCPP(); 
??? = mcpp.get_Points();  // what should be ???  

或者是否需要任何类型转换?

请您参考如下方法:

您不能返回类型 cliext::vector< T > 因为它没有公开声明。但是,您可以将其转换为 IEnumerable< T >:

   IEnumerable<System::Drawing::Point>^ ManagedCPP::Points::get() { 
 
     auto corners = gcnew cliext::vector<ystem::Drawing::Point>(); 
      for (auto &point : points) { 
         corners->push_back(System::Drawing::Point(points.x, points.y)); 
     } 
     return corners; 
  } 

或者,您可以返回一个标准的 .NET 容器(列表或数组)。

array<System::Drawing::Point>^ ManagedCPP::Points::get() { 
 
    auto list = gcnew List<System::Drawing::Point>(points.size()); 
    for(auto & point: points) { 
       list->Add(System::Drawing::Point(point.x, point.y)); 
    } 
 
    return list->ToArray(); 
}