Question

Hello i have the following function which i use afterwards from c# to display a bitmap with "Bitmap.FromHbitmap(IntPtr)" but after a few usages this ends with a memory leak .

IntPtr GetFrame(int Width,int Height,int nFrame)
    {
        width= Width;
        height = Height;
        HBITMAP hb;
        m_piHelper->GetBmp(width,height,nFrame,&hb);    
        return IntPtr(hb);
    }

Probably i should deleteobject somewere but i dont know where i could do that i tried before return but i end up with no image but a gdi error

Thank you,

Was it helpful?

Solution

I assume you are using C#.

You can use DeleteObject to delete this HBITMAP.

Declare it like this:

using System.Runtime.InteropServices class API { [DllImport("WINGDI32.dll")] public static extern int DeleteObject(IntPtr hObject); }

And delete the object:

API.DeleteObject(hBitmap);

As your function returns a pointer to the HBITMAP, you cannot delete it before return. Instead, you should delete it later enough when there will be no more use of this bitmap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top