Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal - Do I need to free any resources?

I am using below method to convert byte[] to Bitmap:

    public static Bitmap ByteArrayToBitmap(byte[] byteArray)
    {
        int width = 2144;
        int height = 3;
        Bitmap bitmapImage = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
        BitmapData bmpData = bitmapImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
        IntPtr ptr = bmpData.Scan0;

        try
        {
            Marshal.Copy(byteArray, 0, ptr, byteArray.Length);
            bitmapImage.UnlockBits(bmpData);
            return bitmapImage;
        }
        finally
        {
           //Marshal.FreeHGlobal(ptr); //Do I need this?
        }
    }

Just wondering if I need to free up any resources here? Tried calling Marshal.FreeHGlobal(ptr), but I am getting this error:

Invalid access to memory location.

Can anyone please guide?

Also, FYI, I could use MemoryStream to get Bitmap out of byte[], but I was getting 'Parameter not valid' exception in that case. That's why took the route to Marshal.

like image 571
inutan Avatar asked Feb 02 '14 18:02

inutan


3 Answers

You only use FreeHGlobal when you used AllocHGlobal. You didn't so don't call it. You did allocate unmanaged memory, it was done by new Bitmap. That's released by Dispose() or the GC. Later.

You certainly should use that finally block, that's where you call UnlockBits(). That 'releases' the pointer.

like image 192
Hans Passant Avatar answered Oct 15 '22 05:10

Hans Passant


No you do not need to.

The memory that is allocated for the bitmap is allocated by the Bitmap constructor and it will be freed when the bitmapImage gets disposed.

like image 2
Trifon Avatar answered Oct 15 '22 07:10

Trifon


The only thing you should do is be sure you call dispose on the returned Bitmap. The best way to do that is placing it within using block.

using(Bitmap myBitmap = ByteArrayToBitmap(someArray)
{
   //...
}
like image 1
MarcinJuraszek Avatar answered Oct 15 '22 07:10

MarcinJuraszek