tags:

views:

548

answers:

2

Here is what I have:

  • An external DLL, I have written in C. This DLL links to opencv. I don't want to call OpenCV directly from C# - there are already huge amounts of C code accessing OpenCV which will be used in the DLL. There is an exported function: passbitmap(void *mem, size_t s);

  • A C# project from which I want to call the DLL.

  • A System.Drawing.Bitmap object from which I want to pass the pixel/bitmap data somehow to my DLL.

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?

+2  A: 

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().

jeffamaphone
+1  A: 

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.

Tim Jarvis