I’ll explain my situation first: I’m interested of using the Bitmap constructor that takes scan0, stride and format, because I’m decoding tiled images and I’d like to choose my own stride so I can decode the tiles without caring about the bounds in the decoder part.
Anyway, the problem is that the documentation says:
The caller is responsible for allocating and freeing the block of memory specified by the scan0 parameter. However, the memory should not be released until the related Bitmap is released.
I can’t release the buffer easily, because the Bitmap is then passed to another class that will eventually destroy it and I don’t have control over it. Is there some way (hacky, I know) to tell the GC to also release my buffer when the Bitmap is destroyed?
(Also, any alternative solution is welcome).
Have a look at the ConditionalWeakTable<TKey, TValue> Class. It’s a special dictionary class where the keys are weakly referenced, and the values are kept alive as long as the key is alive.
You could instantiate a ConditionalWeakTable<Bitmap, UnmanagedMemoryHandle> where UnmanagedMemoryHandle is a custom class that contains the pointer to the unmanaged memory and releases that memory when it’s disposed or finalised. The Bitmap would be weakly referenced by the table; UnmanagedMemoryHandle will be kept alive as long as the Bitmap lives, so the unmanaged memory will be freed when the Bitmap is garbage collected.