我正在使用 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 中执行此操作的正确方法时遇到了问题。任何建议将不胜感激。谢谢!
最佳答案
要返回 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;
}
现在,您还可以在这里做其他的事情。特别是,您可能想要构造某种 .Net 图像类型并返回它,而不是返回整数数组。
关于c++-cli - 将 C++/CLI 中的 int 数组返回到 c# .NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27492520/