c++ - 如何在c++/cli中正确释放Bitmap的 'external'像素数据

标签 c++ .net opencv bitmap

在我的情况下,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/

相关文章:

c++ - 编译 C++ 源代码以获得最大的可移植性

c++ - 在 Rcpp 中构建数据框

.net - 运行 Excel DNA FSharp 注册示例时出现 DnaMarshalException

.net - 站点 "Notes And Attachments"的 Salesforce SOQL 查询

opencv - 查找具有2D和3D对应关系的两个摄像机之间的相对姿势

c++ - Opencv 3.0.0、C++、Visual Studio 2015 - 查找轮廓和 ConvexHull 时出错

c++ - 使用灰度时调试断言失败

c++ - VS2008 中的 Libssh 服务器身份验证进展不顺利

c++ - 从命令行获取参数的问题

c# - 使用验证覆盖列表中的 .Add 方法