预备知识: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; //完成使命后,直接退出,不让它进入事件循环 }