Groups | Blog | Home
all groups > dotnet interop > september 2007 >

dotnet interop : Converting GDI+ Bitmap from unmanaged code to managed code


Cartoper
9/11/2007 8:53:15 AM
I have a very simple (I think) question: How do I convert a unmanaged
GDI+ bitmap into a managed GDI+ Image? The code is C++ CLI (.Net
2.0). There is another option, the Bitmap is being generated by
calling it's function UnlockBits() that takes a unmanaged
Gdiplus::BitmapData structure. Is it easier/safer to convert the
unmanaged Gdiplus::BitmapData structure and pass that into a managed
Bitmap object's UnlockBits() method?
Cartoper
9/11/2007 9:19:39 AM
On Sep 11, 12:06 pm, "Michael Phillips, Jr."
[quoted text, click to view]

I major concern is not ease, but speed. The unmanaged code is
manipulating the data in the unmanaged BitmapData.Scan0 to generate
the image for display. When using the LockBits() call, the
ImageLockModeUserInputBuf flag is being set. Is it possible to simply
cast the unmanaged BitmapData to a managed BitmapData?
Michael Phillips, Jr.
9/11/2007 12:06:58 PM
[quoted text, click to view]

There are many ways to Marshal a gdiplus bitmap between managed and
unmanaged code.

Here are a few methods:
1) You may use GetHBITMAP() to pass a handle to a bitmap.
2) You may use a stream to represent the bitmap.
3) You may use a global memory pointer to a packed DIB(i.e.,
BITMAPINFOHEADER, ColorTable, bits).
4) You may use a IPictureDisp interface.

Choice #1 is the easiest to implement.

Michael Phillips, Jr.
9/11/2007 12:47:37 PM
[quoted text, click to view]

No. LockBits provides a copy of the bitmap's memory for the rectangular
region passed.

When the lock is released the memory copy is committed to the image.

You can use GCHandle.Alloc to pin the memory for the bitmap when it is
created or
you can use CreateDIBSection to create your bitmap.

The pointer to the DIB's memory can be passed back and forth between managed
and unmanaged memory.

There is no protection offered. Reading and writing occur at your peril.

[quoted text, click to view]

AddThis Social Bookmark Button