假設外部第三方庫為 test.h,test.lib,test.dll,
調用的函數是 int fnTest(int param);
一、VS中的靜態調用和動態調用
1.1 靜態調用
靜態調用需要用到第三方的文件:.h .dll .lib
靜態調用跟使用本項目內的函數差不多,區別的一點在於本項目內的函數要在被調用之前聲明,靜態調用需要把第三方的頭文件(.h)和lib文件導入到項目中。
導入第三方庫的方法有2種:
①.在使用第三方庫的文件中加入
#include "test.h" #pragma comment(lib,"test.lib")/*根據.h和.lib存放的路徑設置*/ //調用時直接使用fnTest函數即可; int result = fnTest(4);
②.在項目-屬性中設置
添加頭文件:在屬性界面,C++->常規->附加包含目錄中加入頭文件 test.h;
添加lib文件,在屬性界面,鏈接器->常規->附加庫目錄中加入lib文件所在的目錄 鏈接器->輸入->附加依賴項中加入lib文件 test.lib;
注意上述的分號不要省略。
調用時直接使用fnTest函數即可;
int result = fnTest(4);
1.2 動態調用
當只有.dll文件時,可以采用動態調用;動態調用步驟如下:
//1.定義一個指針函數 typedef void(*fun) typedef int(*funcTest)(int); //2.定義一個句柄,獲取dll的地址 HINSTANCE hDLL = LoadLibrary("test.dll"); if(nullptr == hDLL) { string s = "can not find dll"; throw std::exception(s.c_str()); } //3.定義一個函數指針獲取函數地址 funcTest test = (funcTest)GetProcAddress(hDLL,"fnTest"); if(nullptr == test) { string s = "can not find function:fnTest"; throw std::exception(s.c_str()); } //4.通過定義的函數指針調用函數 int iResult = test(5); //最后一定要記得釋放句柄,上述2,3,4步驟如果失敗也要釋放句柄 FreeLibrary(hDLL);
二、QT中的顯式調用和隱式調用
2.1 隱式調用
QT的隱式調用與C++靜態調用相似,兩種方法
①.與C++靜態調用方式相同;
②.在.pro文件空白位置單擊右鍵,添加庫
在庫類型中選擇"外部庫",下一步,選擇對應的庫文件,平台和鏈接根據需要選擇,下一步,完成.
然后再進行①操作.
2.2 顯示調用
QT提供QLibrary類顯式調用外部工具,具體步驟如下:
//1.定義一個指針函數 typedef void(*fun) typedef int(*funcTest)(int); //2.定義一個QLibrary類,加載dll QLibrary qlibDLL("test.dll); if(!qlibDLL.load())//加載dll { string s = "can not find dll"; throw std::exception(s.c_str()); } //3.定義一個函數指針獲取函數地址 funcTest test = (funcTest)qlibDLL.resolve("fnTest"); if(nullptr == test) { string s = "can not find function:fnTest"; throw std::exception(s.c_str()); } //4.通過定義的函數指針調用函數 int iResult = test(5); //5.釋放內存 qlibDLL.unload();