[Mono-list] issue with pinvoke & memory leak

Ravindra rkumar@novell.com
Wed, 02 Jun 2004 17:08:39 +0530


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