如何将 std::vector<std::vector<int>> 从 C++ 返回到 C++/CLI?

How to return std::vector<std::vector<int>> from C++ to C++/CLI?

本文关键字:std C++ lt gt vector CLI 返回 int      更新时间:2023-10-16

在我的解决方案中,我有c++/CLI (vs2012)项目,在c++ (vs2010)项目中执行一些方法。以下是本机代码的签名:

    void Pcl::Downsample(std::vector<CloudPointNative>& points, std::vector<std::vector<int>>& clusters)

下面是我如何在c++/CLI端执行它:

    std::vector<std::vector<int>> clusters;
    pcl->Downsample(points, clusters);

然后我尝试遍历集群:

    for (int clusterIndex = 0; clusterIndex < clusters.size(); clusterIndex++)
    {
        auto cluster = clusters[clusterIndex];

簇的大小为7,向量中的每一项都包含int类型的向量。我可以在本机端的调试器中看到这个。一旦我回到托管端(c++/cli项目),我就会遇到问题。如果clusterIndex == 0, clusterIndex == 5,则正常工作。但是对clusterIndex的任何其他值抛出AccessViolationException。

auto cluster0 = clusters[0]; // works
auto cluster1 = clusters[1]; // AccessViolationException
auto cluster5 = clusters[5]; // works

这是怎么回事?

解决。我已将签名更改为:

std::vector<std::vector<int>*>* Pcl::Downsample(std::vector<CloudPointNative>& points)

并增加了Free方法来删除向量

void Pcl::Free(std::vector<std::vector<int>*>* clusters)
{
   for(int i = 0; i < clusters->size(); i++)
   {
      delete (*clusters)[i];
   }
   delete clusters;
}

因为在外部DLL中创建的对象也应该在外部DLL中删除