George
George

Reputation: 15551

How can I pass a .NET Bitmap to a native DLL?

Here is what I have:

I guess its some kind of P/Invoke, but I have never done it, and don't know how can I do it properly in this case. How should I proceed?

Upvotes: 1

Views: 3603

Answers (2)

Tim Jarvis
Tim Jarvis

Reputation: 18815

The C function prototype simply wants a pointer to a buffer and the size of the buffer, what it expects to see inside the buffer is the $64K question. My assumption / wild guess is that it's the Bitmap bits in a ByteArray form. So...

I guess this needs to be broken down into steps...

[untested, but I think the general idea is sound]

* get the data from your bitmap, into probably a Byte Array
* allocate an unmanaged buffer to store the data
* copy the byte array to the buffer.
* Pass the buffer pointer to your C dll
* Free the buffer when you are done

you can allocate an unmanaged buffer using

IntPtr pnt = Marshal.AllocHGlobal(size);

and you can copy your byte array using

Marshal.Copy(theByteArray, 0, pnt, theByteArray.Length);

Note, because its unmanaged data, you will be responsible for freeing it when you are done.

Marshal.FreeHGlobal(ptr)

Note, as @jeffamaphone says, if you have access to the c code, it would be much better to simply pass the bitmap handle around.

Upvotes: 1

i_am_jorf
i_am_jorf

Reputation: 54600

You need to call Bitmap.GetHbitmap() to get the native handle to the bitmap.

Then you basically want to do some native interop and call GetDIBits(). It may be better to have your target dll actually call GetDIBits() and just pass the win32 handle, rather than do the interop.

You'll need to call CreateCompatibleDC() on the desktop DC which you get from GetDC(NULL), then CreateCompatibleBitmap() on the DC you just made. Then call GetDIBits().

Upvotes: 4

Related Questions