在我的情况下,Drawing::Bitmap 是使用指向像素数据的指针创建的。在 MSDN 上,您可以找到一个构造函数,它正是这样做的:
Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);
从文档中可以清楚地看出,此构造函数仅创建 header 和所提供数据周围所需的内容。还需要注意的是,调用者必须释放像素数据数组。
The caller is responsible for allocating and freeing the block of memory specified by the scan0 parameter. However, the memory should not be released until the related Bitmap is released.
我的问题是,如果我将带有链接像素数据的位图传递给另一个类,那么我将无法释放底层数据。请参阅下面的示例:
Drawing::Image^ FirstClass::GetImage(std::string ImagePath)
{
IplImage* cvImg = cvLoadImage(ImagePath.c_str());
Drawing::Image^ ManagedImg = gcnew Bitmap(
cvImg->width,
cvImg->height,
cvImg->widthStep,
Drawing::Imaging::PixelFormat::Format24bppRgb,
(System::IntPtr)cvImg->imageData);
return ManagedImg;
}
Void SecondClass::RefreshImage()
{
// Release the last image first
if (MyImage!=nullptr)
{
???
}
MyImage = GetImage(...);
}
一个简单的解决方法是将 IplImage* 传递给 SecondClass,在那里创建托管的 Bitmap 然后调用 cvReleaseImage(&Native_MyImage) ;那里。不管怎样,我真的很想知道如何在不通过 IplImage* 的情况下正确地做到这一点。
最佳答案
您需要以某种方式将指针传递给像素。
对我来说,更好的方法是将 IplImage*
和 ManagedImg
包装到一个管理它们的类中。该类的析构函数将负责销毁 ManagedImg
,然后调用 cvReleaseImage()
以获取 IplImage*
的存储值。然后您的 GetImage
函数可以返回指向此包装类的指针,而不是指向 Drawing::Image
的指针。
关于c++ - 如何在c++/cli中正确释放Bitmap的 'external'像素数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18681930/