我正在将图像数据从C#脚本发送到C ++ dll。我想知道如何将这些数据转换回C ++端的图像,以便随后可以使用GDI +显示。
C#代码
[DllImport("ExtWindow")]
private static extern void SetImage(IntPtr img, int width, int height);
(...)
using (var bmp = new Bitmap(@"D:/my_image.png"))
{
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
SetImage(bmp.GetHbitmap(), bmp.Width, bmp.Height);
bmp.UnlockBits(data);
}
C ++代码
Bitmap* display_img;
extern "C" void __declspec(dllexport) SetImage(void* data, int width, int height) {
HBITMAP hBmp = CreateBitmap(width, height, 1, 24, data);
display_img = (Bitmap*)Bitmap::FromHBITMAP(hBmp, NULL); // <=== i fail to properly convert here
// Force WM_PAINT
RedrawWindow(my_hWnd, 0, 0, RDW_INVALIDATE | RDW_UPDATENOW);
}
(...) // A window is created earlier, which is where the image will be displayed
LRESULT CALLBACK newWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message)
{
case WM_PAINT:
// Display the image
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
Graphics graphics(hdc);
graphics.DrawImage(display_img, 0, 0);
EndPaint(hWnd, &ps);
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
假设它是相同的过程,则可以传递HBITMAP
句柄。除非直接访问位,否则不需要锁定位(这在进程间操作中通常是必需的)
在C#端:
SetImage(bmp.GetHbitmap());
在C ++方面,请确保已调用[C0]例程,并读取了Gdiplus::GdiplusStartup
。您可以直接使用GDI打印HBITMAP
,或转换为hbitmap
以在Gdiplus中打印
Gdiplus::Bitmap