tags:

views:

197

answers:

2

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class.

My import looks like this:

[DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr GetBitmap(System.IntPtr hwnd, int nBMPWIDTH, int nBMPHEIGHT);

The H file section looks like:

Cbitmap* GetBitmap(HWND hwnd,int nBMPWIDTH,int nBMPHEIGHT);

How do I go about converting the Cbitmap into something I can display in C#?

Many thanks.

+1  A: 

The closest API in the .NET Framework is Image.FromHbitmap, but this would require you to extract the HBITMAP from the CBitmap, which you can't do in C# (at least not without knowing the internals of CBitmap). If it's possible for you to modify your C++ GetBitmap function to return the HBITMAP rather than the CBitmap wrapper, that would be the easiest solution. Is that an option for you?

itowlson
Seconded. You'll have to get the HBITMAP from the CBitmap, which you'll have to do in C++. You technically can marshal a class, but you'd have to know it's Exact memory layout.
shf301
I do not have access to the c++ dll source. What can I do? Thank you.
Myakka
Create a small C++ function as follows: HBITMAP GetHandle(CBitmap* pBitmap) { return (HBITMAP)( * pBitmap); }. Then P/Invoke this, passing your CBitmap IntPtr. The returned IntPtr is the HBITMAP. (The reason for still having the CBitmap * is so you can defer freeing it until you've finished with the HBITMAP; otherwise the CBitmap destructor will trash the handle for you I believe.)
itowlson
Would I create this C++ function in managed CLR c++? or win32? Thank you.
Myakka
I was thinking native C++. But you're probably right that it could also be done in C++/CLI, in which case you wouldn't need to P/Invoke the wrapper because it would be a .NET-to-.NET call (and the transition to native code would happen within your C++/CLI assembly).
itowlson
A: 

Unfortunately I have no a access to the c++ dll source. Is there a way to do it in this case? I tried a memory stream without any luck. Thank you.

Myakka
how you plan to delete the returning object? MFC's delete operator is not available in C#.
Sheng Jiang 蒋晟