我使用C ++ / CLI包装器从c#.NET调用c ++库。虽然这个特殊的代码"有效,"我怀疑我在记忆方面做错了什么。 (连续20次运行此代码后,我遇到了问题。)
c#side:
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中找出正确的方法时遇到了问题。任何建议将不胜感激。谢谢!
答案 0 :(得分:3)
要返回一个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图像类型并返回该类型,而不是返回整数数组。