highsmallxu/aforge

GC.KeepAlive for UnmanagedImages

Opened this issue · 2 comments

What steps will reproduce the problem?
1. Build the attached program.
2. Run the attached program outside of the debug environment.
3. Inspect the generated test.png file.


What is the expected output? What do you see instead?

The file should be black. Running under a debug environment it will be. Running 
under an optimizing JIT it will be white, unless you uncomment the GC.KeepAlive 
line.


What version of the product are you using?

AForge.NET Framework-2.2.5.
Tested under .NET version 2.0.50727.8009 and 4.0.30319.34209.


Please provide any additional information below.

This happens because after you obtain the ImageData pointer, the GC is free to 
garbage collect the UnmanagedImage (even though it is a function parameter, 
apparently in scope).

This will free the unmanaged memory allocated for the image, and the second 
image will be allocated in its place. Setting all bytes on ImageData to white 
will thus affect the second image. The solution here is to uncomment the 
GC.KeepAlive line.

There are an awful lot of places where AForge does something similar across the 
entire framework (e.g. obtain the pointer, and go through the image using an 
unsafe block, which by the way, in no way prevents this optimization). It's 
terribly hard to get a comprehensive fix. User code (e.g. the Accord framework) 
also does this a lot.

Typically this won't cause problems, but it's there waiting to happen, whenever 
an UnmanagedImage might be freed by the GC (and not duly disposed of).

Original issue reported on code.google.com by ncruces on 5 Mar 2015 at 7:15

Attachments:

One thing that is noteworthy is that using System.Drawing.Bitmap instances with 
AForge is safe, because the UnlockBits method (which is always called after 
processing) keeps a reference to the bitmap.

Another is that dully disposing of all UnmanagedImage instances is also safe.


I'll be providing a first patch that goes through all the Filter base classes 
and fixes it for subclasses, if you're interested. But it's only just 
scratching the surface of the problem.

Original comment by ncruces on 5 Mar 2015 at 7:18

Attached a patch that fixes this for the areas of AForge I'm using: mostly 
filters, blob detection and color quantization.

Original comment by ncruces on 6 Mar 2015 at 8:03

Attachments: