24小时热门版块排行榜    

查看: 869  |  回复: 0

yalefield

金虫 (文坛精英)

老汉一枚

[交流] 【转帖】Windows下如何使用QT编写DLL程序

作者:tingsking18
http://blog.csdn.net/tingsking18/archive/2009/12/08/4967172.aspx

因为QT必须有调用QApplication的exec方法,这样才能产生消息循环,QT的程序才可以运行。所以说,如果我们使用了QT编写了DLL程序,在普通的windows程序中是不能调用的。在调用的时候会出现错误。当然QT提供了解决方法:那就是QTWinmigrate(这里是QT官方网站对QTWinmigrate的介绍:http://doc.trolltech.com/solutions/qtwinmigrate/winmigrate-walkthrough.html)

下面我来介绍一下使用QTWinmigrate来编写DLLl的方法。

首先,我们要重写DllMain函数:
CODE:
   1. #include   
   2. #include   
   3. #include   
   4. #include   
   5. BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID lpvReserved )  
   6. {  
   7.     static bool ownApplication = FALSE;  
   8.     if ( dwReason == DLL_PROCESS_ATTACH )  
   9.         ownApplication = QMfcApp::pluginInstance( hInstance );  
  10.     if ( dwReason == DLL_PROCESS_DETACH && ownApplication )  
  11.         delete qApp;  
  12.     return TRUE;  
  13. }  

大家都知道DllMain函数是windows动态库的入口函数,在DLL中使用QT的UI界面之前,必须首先要创建全局的QApplication,并且应用程序必须创建EventLoop。

进入到QmfcApp::pluginInstance方法中去,可以看到:Qapplication被创建了出来。QmfcApp::pluginInstanc是为了保证进程中存在一个Qapplication对象,并且dll要把这个Qapplication的实例加载到内存中。
CODE:
   1. bool QMfcApp::pluginInstance(Qt::HANDLE plugin)  
   2. {  
   3.     if (qApp)  
   4.     return FALSE;  
   5.     QT_WA({  
   6.     hhook = SetWindowsHookExW(WH_GETMESSAGE, QtFilterProc, 0, GetCurrentThreadId());  
   7.     }, {  
   8.     hhook = SetWindowsHookExA(WH_GETMESSAGE, QtFilterProc, 0, GetCurrentThreadId());  
   9.     });  
  10.     int argc = 0;  
  11.     (void)new QApplication(argc, 0);  
  12.     if (plugin) {  
  13.     char filename[256];  
  14.     if (GetModuleFileNameA((HINSTANCE)plugin, filename, 255))  
  15.         LoadLibraryA(filename);  
  16.     }  
  17.   
  18.     return TRUE;  
  19. }  

下面是DLL中的导出函数:
CODE:
   1. extern "C" __declspec(dllexport) bool showDialog( HWND parent )  
   2. {  
   3.     QWinWidget win( parent );  
   4.     win.showCentered();  
   5.     QMessageBox::about( &win, "About QtMfc", "QtMfc Version 1.0\nCopyright (C) 2003" );  
   6.   
   7.     return TRUE;  
   8. }  

DLL中的导出函数,要用extern "C"形式,QwinWidget为native win32窗口提供堆栈等等。

这样还没有写完程序!如果你仔细看qtwinmigrate的example的话,你就会注意到:
CODE:
include(D:\qt4.4.3\qtwinmigrate-2.8-opensource\src\qtwinmigrate.pri)

编译的时候一定要在*.pro文件中加上这一句!切记,切记!(老汉按:例子中,默认的,Qt是安装在D:\qt4.4.3\目录下)。

[ Last edited by yalefield on 2011-1-30 at 23:52 ]
回复此楼

» 猜你喜欢

已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 yalefield 的主题更新
普通表情 高级回复 (可上传附件)
信息提示
请填处理意见