Yochai Timmer
Yochai Timmer

Reputation: 49261

Solution for unmanaged buffer assigned to a managed Image

I have a char* buffer of a bitmap image that I'm getting from a native DLL.

I'm using C++/CLI to export the native DLL to .Net

I want to create a Drawing.Bitmap object form that buffer without an extra copy.
This can be done with one of the constructors.

The problem is managing the memory, how can I delete the buffer when the Image is collected by the GC ?

I would like to extend Bitmap, keep a pointer to the buffer, and override the destructor.

But, as you know, Bitmap is sealed, and Image can't be inherited....
Any ideas ?

Upvotes: 0

Views: 392

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283803

Congratulations, you've run into a prime example of why it's strongly recommended for DLLs to fill in a caller-supplied buffer instead of returning a pointer to memory allocated within the DLL. By using a caller-supplied buffer, you allow the caller to manage its lifetime using whatever method he likes. C++ callers can use smart pointers. .NET callers can use garbage collection. Buffers associated with images can be owned by the Bitmap instance.

In your case, the best solution is to create the Bitmap of the appropriate size and pixel format, call LockBits to get access to its internal buffer, and pass a pointer to that buffer to the DLL which can then place its output directly into the bitmap. Finally, call UnlockBits.

Upvotes: 3

Related Questions