用QT在Windows下編寫dll程式

來源:互聯網
上載者:User

因為QT必須有調用QApplication的exec方法,這樣才能產生訊息迴圈,QT的程式才可以運行。所以說如果我們使用了QT編寫了dll程式,在普通的 windows程式中是不能調用的。在調用的時候會出現錯誤。當然QT提供瞭解決方法:那就是QTWinmigrate

這裡是QT官方網站對QTWinmigrate的介紹:

http://qt.nokia.com/products/appdev/add-on-products/catalog/4/Windows/qtwinmigrate

下面我來介紹一下使用QTWinmigrate來編寫dll的方法。

首先,我們要重寫DllMain函數:

#include <qtwinmigrate/qmfcapp.h>
#include <qtwinmigrate/qwinwidget.h>
#include <qmessagebox.h>
#include <windows.h>
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;
}

大家都知道DllMain函數是windows動態庫的入口函數,如果在dll中使用了QT的ui介面前,全域的QApplication必須首先 要建立,並且應用程式必須建立EventLoop。

進入到QmfcApp::pluginInstance方法中去,

bool QMfcApp::pluginInstance(Qt::HANDLE plugin)
{
    if (qApp)
return FALSE;
    QT_WA({
hhook = SetWindowsHookExW(WH_GETMESSAGE, QtFilterProc, 0, GetCurrentThreadId());
    }, {
hhook = SetWindowsHookExA(WH_GETMESSAGE, QtFilterProc, 0, GetCurrentThreadId());
    });
    int argc = 0;
    (void)new QApplication(argc, 0);
    if (plugin) {
char filename[256];
if (GetModuleFileNameA((HINSTANCE)plugin, filename, 255))
     LoadLibraryA(filename);
    }

    return TRUE;
}
我們可以看到:Qapplication被建立了出來。QmfcApp::pluginInstanc是為了保證進程中存在一個Qapplication 對象,並且dll要把這個Qapplication的執行個體載入到記憶體中。

下面是dll中的匯出函數:

extern “C” __declspec(dllexport) bool showDialog( HWND parent )
{
    QWinWidget win( parent );
    win.showCentered();
    QMessageBox::about( &win, “About QtMfc”, “QtMfc Version 1.0/nCopyright (C) 2003″ );

    return TRUE;
}
dll中的匯出函數要用extern “C”形式,QwinWidget為native win32視窗提供堆棧等等。

這樣還沒有寫完程式。不行你拿這個程式來

qmake -project

qmake

nmake

這樣是無論如何也編譯不過的。

如果你仔細看qtwinmigrate的example的話,你就會注意到:

include(D:/qt4.4.3/qtwinmigrate-2.8-opensource/src/qtwinmigrate.pri)

編譯的時候一定要在*.pro檔案中加上

更多關於QT的詳細資料,或者請點這裡

轉帖自:http://www.meegox.com/1018.html
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.