C++ cli 将C++/CLI中的int数组返回到C.NET 我使用C++/CLI包装器从C++ .NET调用C++库。虽然这段特定的代码有效,但我怀疑我在内存方面做了一些错误的事情。在连续20次运行此代码后,我遇到了问题

C++ cli 将C++/CLI中的int数组返回到C.NET 我使用C++/CLI包装器从C++ .NET调用C++库。虽然这段特定的代码有效,但我怀疑我在内存方面做了一些错误的事情。在连续20次运行此代码后,我遇到了问题,c++-cli,C++ Cli,丙方: public void ExportModelToImage(int[] myImage, int imageWidth, int imageHeight) { View.ExportModelToImage(ref myImage, imageWidth, imageHeight); } C++/CLI端: void ExportModelToImage(array<int>^% myImage, int imageWidth, int imageHeight)

丙方:

public void ExportModelToImage(int[] myImage, int imageWidth, int imageHeight)
{
    View.ExportModelToImage(ref myImage, imageWidth, imageHeight);
}
C++/CLI端:

void ExportModelToImage(array<int>^% myImage, int imageWidth, int imageHeight)
{
    if (myView().IsNull())
    {
        return;
    }
    myView()->Redraw();
    Image_PixMap theImage;
    myView()->ToPixMap(theImage, imageWidth, imageHeight);

    const int totalBytes = imageWidth * imageHeight;
    int byteIndex = 0;      
    Standard_Integer si = 0;
    Quantity_Color aColor;
    Quantity_Parameter aDummy;
    for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
    {
        for (Standard_Size aCol = 0; aCol < theImage.SizeX(); ++aCol) 
        {
            aColor = theImage.PixelColor((Standard_Integer )aCol, (Standard_Integer )aRow, aDummy);
            aColor.Color2argb(aColor, si);
            myImage[byteIndex] = (int) si;
            byteIndex++; 
            if (byteIndex > totalBytes) return;
         }
    }
}

理想情况下,我更希望ExportModelToImage返回一个int数组,而不是通过引用返回,但在C++/CLI中,我很难找到正确的方法。如有任何建议,将不胜感激。谢谢

若要返回int数组,请使用array^作为返回类型,并使用gcnew初始化局部变量。打电话给gcnew时,别忘了关掉“^”


现在,也就是说,你可以在这里做其他的事情。特别是,您可能希望构造某种类型的.Net映像类型并返回该类型,而不是返回整数数组

谢谢大家!!这是一个主要的帮助。数组部分给我的错误是类模板std::array的参数太少。我该怎么办?
array<int>^ ExportModelToImage(int imageWidth, int imageHeight)
{
    array<int>^ result = gcnew array<int>(imageWidth * imageHeight);

    if (myView().IsNull())
    {
        return nullptr;
        // could also return a zero-length array, or the current 
        // result (which would be an all-black image).
    }
    myView()->Redraw();
    Image_PixMap theImage;
    myView()->ToPixMap(theImage, imageWidth, imageHeight);

    int byteIndex = 0;      
    Standard_Integer si = 0;
    Quantity_Color aColor;
    Quantity_Parameter aDummy;
    for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
    {
        for (Standard_Size aCol = 0; aCol < theImage.SizeX(); ++aCol) 
        {
            aColor = theImage.PixelColor((Standard_Integer )aCol, (Standard_Integer )aRow, aDummy);
            aColor.Color2argb(aColor, si);
            result[byteIndex] = (int) si;
            byteIndex++; 
        }
    }

    return result;
}