預備知識:api
一、若是在沒有導入庫文件(.lib),而只有頭文件(.h)與動態連接庫(.dll)時,咱們才須要顯示調用,若是這三個文件都全的話,咱們就能夠使用簡單方便的隱式調用。app
二、一般Windows下程序顯示調用dll的步驟分爲三步(三個函數):LoadLibrary()、GetProcAdress()、FreeLibrary()函數
其中,LoadLibrary() 函數用來載入指定的dll文件,加載到調用程序的內存中(DLL沒有本身的內存!)指針
GetProcAddress() 函數檢索指定的動態連接庫(DLL)中的輸出庫函數地址,以備調用code
FreeLibrary() 釋放dll所佔空間 orm
一、顯示調用 事件
Qt提供了一個 QLibrary 類供顯示調用。下面給出一個完整的例子:內存
#include <QApplication> #include <QLibrary> #include <QDebug> #include <QMessageBox> #include "dll.h" //引入頭文件 typedef int (*Fun)(int,int); //定義函數指針,以備調用 int main(int argc,char **argv) { QApplication app(argc,argv); QLibrary mylib("myDLL.dll"); //聲明所用到的dll文件 int result; if (mylib.load()) //判斷是否正確加載 { QMessageBox::information(NULL,"OK","DLL load is OK!"); Fun open=(Fun)mylib.resolve("add"); //援引 add() 函數 if (open) //是否成功鏈接上 add() 函數 { QMessageBox::information(NULL,"OK","Link to Function is OK!"); result=open(5,6); //這裏函數指針調用dll中的 add() 函數 qDebug()<<result; } else QMessageBox::information(NULL,"NO","Linke to Function is not OK!!!!"); } else QMessageBox::information(NULL,"NO","DLL is not loaded!"); return 0; //加載失敗則退出28}
myDLL.dll爲自定義的dll文件,將其複製到程序的輸出目錄下就能夠調用。顯然,顯示調用代碼書寫量巨大,實在不方便。it
二、隱式調用io
這個時候咱們須要三個文件,頭文件(.h)、導入庫文件(.lib)、動態連接庫(.dll),具體步驟以下:
一、首先咱們把 .h 與 .lib/.a 文件複製到程序當前目錄下,而後再把dll文件複製到程序的輸出目錄,
二、下面咱們在pro文件中,添加 .lib 文件的位置: LIBS+= -L D:/hitempt/api/ -l myDLL
-L 參數指定 .lib/.a 文件的位置
-l 參數指定導入庫文件名(不要加擴展名)
另外,導入庫文件的路徑中,反斜槓用的是向右傾斜的
三、在程序中include頭文件(我試驗用的dll是用C寫的,所以要用 extern "C" { #include "dll.h" } )
下面是隱式調用的實例代碼:
#include <QApplication> #include <QDebug> extern "C" //因爲是C版的dll文件,在C++中引入其頭文件要加extern "C" {},注意 { #include "dll.h" } [cpp] view plain copy int main(int argv ,char **argv) { QApplication app(argv,argv); HelloWordl(); //調用Win32 API 彈出helloworld對話框 qDebug()<<add(5,6); // dll 中我本身寫的一個加法函數 return 0; //完成使命後,直接退出,不讓它進入事件循環 }