Monday, December 17, 2007

Avoid Memory Leaks with FromHBitmap and GetHbitmap

In VB6 we called .Handle to get a handle to an image, which I then passed to a C routine.  In order to get a handle to an image in VB.NET, I had to call GetHbitmap.ToInt32 to get a handle.  Then in order to get the image back from that call, I would call FromHBitmap.  Below is an example:

    Public Function DoSomething(ByRef hbmp As Bitmap) As Integer
        Dim returnVal As Integer
        Dim hbmp1 As IntPtr
        If Not hbmp Is Nothing Then
            hbmp1 = hbmp.GetHbitmap 'Get a handle to the image

            returnVal = DoSomethingInC(hbmp1.ToInt32) 'get an Integer Pointer to the Image which is passed to the C routine
            hbmp = Bitmap.FromHbitmap(hbmp1)
            Return returnVal
        Else
            Return MiscError
        End If
    End Function

Now when I did this, I had a memory leak with GetHBitmap and FromHBitmap.  You solve that by calling .Dispose and DeleteObject.  Highlighted below.

    Public Function DoSomething(ByRef hbmp As Bitmap) As Integer
        Dim returnVal As Integer
        Dim hbmp1 As IntPtr
        If Not hbmp Is Nothing Then
            hbmp1 = hbmp.GetHbitmap 'Get a handle to the image

            returnVal = DoSomethingInC(hbmp1.ToInt32) 'get an Integer Pointer to the Image which is passed to the C routine
            If Not hbmp Is Nothing Then hbmp.Dispose()
            hbmp = Nothing
            hbmp = Bitmap.FromHbitmap(hbmp1)
            DeleteObject(hbmp1)
            Return returnVal
        Else
            Return MiscError
        End If
    End Function

A couple of thoughts:
1.  Doing this slows down performance, as the calls to GetHbitmap and FromHBitmap is a lot slower than just calling Image.Handle (in VB6).  I still haven't figured out how to solve the performance hit.
2.  I still have issues with 8 bit images, as in VB.NET we do everything in 32 bit, and previously my C routines were working with 8 bits.  I still haven't figured out a workaround to this.


No comments: