最近在做一些视频或者摄像头硬件设备集成软件时,经常会遇到一些调用c++硬件设备的SDK来实时刷新控件做图像显示。现在来看看整个c#调用c++做图像刷新的实现过程。
vs版本2019: 首先创建一个winfrom 的工程解决方案WinInvoke:
创建完成后在解决方案上创建一个c++的动态链接库WinDll项目
创建后
WinDLL 添加头文件 Paint.h 和 cpp 文件Paint.cpp
在Paint.h 中定义外部接口函数 DrawGraph
extern "C" _declspec(dllexport) int DrawGraph(int width, int height, HDC hdc);
HDC 是传入的控件句柄
Paint.cpp 做实现过程
int DrawGraph(int width, int height, HDC hdc)
{
HBITMAP hSun = (HBITMAP)LoadImage(hInst, L"1.jpg", IMAGE_BITMAP, width, height, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
HDC hMemDc = CreateCompatibleDC(hdc);//获取内存设备描述表句柄,使得 位图能在内存中保存下来
SelectObject(hMemDc, hSun);//选择位图对象,送入内存设备描述表;
BitBlt(hdc, 0, 0, width, height, hMemDc, 0, 0, SRCCOPY);//把位图从内存复制到窗口
DeleteDC(hMemDc);//删除设备内存描述表中的位图
return 1;
}
WinInvoke 工程里添加一个form
代码里引入 c++文件 及接口函数 DrawGraph
private const string dllPath = @"WinDLL.dll";
[DllImport(dllPath, EntryPoint = "DrawGraph", CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern int DrawGraph(int width, int height, IntPtr mhwnd);
from里添加一个控件用来显示图像,这里用picturebox 来显示
添加picturebox 的paint 事件
void pb_Img_Paint(object sender, PaintEventArgs e)
传入HDC 句柄 调用 c++函数做刷新显示
var hdc = e.Graphics.GetHdc();
DrawGraph(pb_Img.Width, pb_Img.Height, hdc);
e.Graphics.ReleaseHdc(hdc);
画完之后要 释放句柄 ReleaseHdc。
代码可以去资源上下载