[英]How do I convert from an unmanaged C++ dll char** to a C# string and back
[英]How do I reconstruct Image data sent from C# to a C++ dll back into an Image
我正在将图像数据从 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++ 端,确保您已调用Gdiplus::GdiplusStartup
例程,并读取HBITMAP
。 可以直接用GDI打印hbitmap
,也可以转换成Gdiplus::Bitmap
在Gdiplus中打印
HBITMAP g_hbitmap = NULL;
extern "C" void __declspec(dllexport) SetImage(HBITMAP hbmp) {
RedrawWindow(my_hWnd, 0, 0, RDW_INVALIDATE | RDW_UPDATENOW);
}
...
case WM_PAINT:
...
if (g_hbitmap)
{
Gdiplus::Bitmap bitmap(g_hbitmap, NULL);
Gdiplus::Graphics gr(hdc);
Gdiplus::Status status = gr.DrawImage(&bitmap, 0, 0);
//check status
//clean up here, or elsewhere
DeleteObject(g_hbitmap);
g_hbitmap = NULL;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.