最近尝试了在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的导出库待后研究......