需求:
一个项目,界面是C# 开发的,但是业务上有三维可视化的需求,VTK基于C#的绑定版本需要收费,并且资料很少。因此将VTK嵌入到Qt里,并封装成一个dll,通过接口提供给C#访问。
实现:
一,Qt程序的配置
这里用到了一第三方库(qt-solutions/qtwinmigrate at master · qtproject/qt-solutions · GitHub),它可以将Qt的窗口给C#使用。
1,首先看pro文件,主要是dll编译配置,和第三方库引用及VTK的依赖库。
2,main.cpp
#include "widget.h" #include <QApplication>#include <windows.h> #include <qmfcapp.h> #include <qwinwidget.h>// int main(int argc, char *argv[]) // { // QApplication a(argc, argv); // Widget w; // w.show(); // return a.exec(); // }BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpvReserved*/ ) {static bool ownApplication = FALSE;if ( dwReason == DLL_PROCESS_ATTACH )ownApplication = QMfcApp::pluginInstance( hInstance );if ( dwReason == DLL_PROCESS_DETACH && ownApplication )delete qApp;return TRUE; }QWinWidget *win=nullptr; extern "C" __declspec(dllexport) bool initWindow( HWND parent ) {if(parent==nullptr)return false;win = new QWinWidget(parent);Widget *widget = new Widget(win);widget->show();win->move(0,0);win->show();return TRUE; }extern "C" __declspec(dllexport) bool destroyWindow() {if(win!=0){win->close();delete win;}return TRUE; }
3,Widget 写法,可以参考这篇文章(集成VTK | Qt hello)或者看仓库上的源码。
二,C#端
1,引用dll 并调用接口
using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace WindowsFormsApp {public partial class Form1 : Form{[DllImport("VTKNet.dll", EntryPoint = "initWindow", CharSet = CharSet.Ansi)]public extern static bool initWindow(IntPtr parent);[DllImport("VTKNet.dll", EntryPoint = "destroyWindow", CharSet = CharSet.Ansi)]public extern static bool destroyWindow();public Form1(){InitializeComponent();//打开窗口initWindow(this.Handle);}} }
2,exe路径下 需要把自己的dll ,Qt的dll 以及VTK的dll 全部放进去。
效果:
C#通过Qt使用VTK | Qt hello
代码:
C#通过Qt使用VTK | Qt hello