我如何将从C#发送到C ++ dll的图像数据重构回图像

问题描述 投票:1回答:1

我正在将图像数据从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);
}
c# c++ image dll gdi+
1个回答
0
投票

假设它是相同的过程,则可以传递HBITMAP句柄。除非直接访问位,否则不需要锁定位(这在进程间操作中通常是必需的)

在C#端:

SetImage(bmp.GetHbitmap());

在C ++方面,请确保已调用[C​​0]例程,并读取了Gdiplus::GdiplusStartup。您可以直接使用GDI打印HBITMAP,或转换为hbitmap以在Gdiplus中打印

Gdiplus::Bitmap
© www.soinside.com 2019 - 2024. All rights reserved.