最近嘗試了在Qt調用VS動態庫的2種方法:顯式加載和隱式加載。Qt版本采用5.1,使用的默認編譯器gcc;VS使用2010。詳細過程如下:
(1)在VS2010中導出動態庫,導出過程未使用windows平台相關的代碼。
1 /*************************************** 2 * MyDll.h 3 ***************************************/ 4 #ifndef MYDLLEXPORT 5 #define MYDLLEXPORT extern "C" __declspec(dllimport) 6 #endif 7 8 9 MYDLLEXPORT int add(int a, int b); 10 MYDLLEXPORT int g_nCount;
1 /*************************************** 2 * DllDemo.cpp 3 ***************************************/ 4 #define MYDLLEXPORT extern "C" __declspec(dllexport) 5 #include "MyDll.h" 6 7 int g_nCount = 0; 8 9 int add(int a, int b){ 10 return (g_nCount += a + b); 11 }
編譯后生成2個文件:DllDemo.lib,DllDemo.dll。
(2)Qt中實現調用
不同調用方式需要的文件不同,對於顯式加載只需要*.dll;隱式加載需要*.h,*.dll。這里只貼出部分代碼如下:
- 顯式
顯式調用需要將*.dll文件復制到生成目錄的執行文件所在路徑下(.exe所在),注意的是Qt Creator中生成目錄是在源碼目錄外的。然后在代碼中Load。
1 QLibrary lib("DllDemo"); // 不需要后綴 2 if (lib.load()) 3 { 4 typedef int(*AddFunction)(int a,int b); 5 AddFunction Add=(AddFunction)lib.resolve("add"); 6 if (Add) 7 { 8 int res = Add(20, 155); 9 ui->lineEdit->setText(QString("%1").arg(res)); 10 } 11 }
- 隱式
隱式加載時在*.pro手動添加:LIBS+=DllDemo.dll,然后倒入所需頭文件,在調用處包含並調用其中的接口即可。
1 /*************************************** 2 * LIBS += DllDemo.dll 3 ***************************************/ 4 #include "MyDll.h" 5 // 隱式調用 6 int res = add(20, 155); 7 ui->lineEdit->setText(QString("%1").arg(res));
以上過程中調用動態庫只是簡單的C函數,關於C++類或包含win32的導出庫待后研究......