在C ++ / CLI返回int数组到C#的.NET(Returning an int array

2019-09-29 16:30发布

我使用的是C ++ / CLI包装调用从C#.NET中的一个C ++库。 虽然这个特殊的代码“的作品,”我怀疑我做错了关于内存。 (我碰上连续运行此代码约20倍后的问题。)

C#的一面:

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。 任何建议将不胜感激。 谢谢!

Answer 1:

返回int阵列,具有array<int>^作为返回类型,并与初始化局部变量gcnew 。 不要忘记留下断^当你调用gcnew

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;
}

现在,这么说,还有其他的可能性,你可以在这里做。 特别是,你可能希望构建某种形式的净图像类型,并返回,而不是返回一个整数数组。



文章来源: Returning an int array in C++/CLI to c# .NET
标签: c++-cli