[Mono-list] issue with pinvoke & memory leak

Chris Turchin chris@turchin.net
Wed, 2 Jun 2004 05:09:49 -0700 (PDT)


Hi Ravindra,

again, thanks for the tip. I checked and the finalizer  was there only it was
not getting called (or not often enough) - i added a GC.Collect() call to my
test class and it worked.

Thanks again!

Regards,

--chris

On Wed, 2 Jun 2004, Ravindra wrote:

> Hello,
>
> On Wed, 2004-06-02 at 17:00, Chris Turchin wrote:
> > i have been playing with  a wrapper for an image library with the following
> > method:
> >
> > private static extern FIBITMAP FreeImage_Rescale(FIBITMAP dib, int dst_width,
> > 					int dst_height, FilterOption filter);
> >
> > I had implemented it like this:
> >
> > public FreeImage Resample(int newwidth, int newheight,
> > 				FilterOption filter)
> >
> > which works fine with something like:
> >
> > FreeImage img2 = img.Resample(100,100,FilterOption.BILINEAR);
> >
> > but when I do:
> >
> > img = img.Resample(100,100,FilterOption.BILINEAR);
> >
> > then the img object is 'replaced' but a I have a big memory leak, since the
> > Dispose() method which handles the cleanup of unmanaged resources (the img
> > object has a pointer to the unmanaged image data which is normally released when
> > the object is disposed) is never called.
> >
> > Can someone give me a tip how to handle this in a way that ensures that the old
> > data from img is disposed in the second case above? Actaully, would this same
> > issue be a problem for all IDisposable objects in managed code (maybe I am not
> > allowed to do this at all with IDisposable objects) or is this unique to the
> > managed/unmanaged code in question here?
>
> Dude, you need to implement finalizer for your FreeImage class.
> Finalizer method would do all the required cleanup you want to do. GC
> would call your class finalizer, when you are done with the referenced
> object.
>
> - Ravindra
>
>