直接上代码
extern "C"{
DLLSHARED_EXPORT Dll* getDllObject(); //获取类Dll的对象
DLLSHARED_EXPORT void releseDllObject(Dll*); //获取类Dll的对象
DLLSHARED_EXPORT void helloWorld();
DLLSHARED_EXPORT int add(int a,int b);
}
#include "mainwindow.h"
#include <QApplication>
#include <iostream>
#include <QLibrary>
#include <windows.h>
#include "dll.h" //头文件还是需要加的,否则无法解析Dll类
typedef Dll* (*CreatDll)();//定义函数指针,获取类Dll对象;
typedef bool (*ReleseDll)(Dll*);
typedef void (*fun)();
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QLibrary mylib("dll.dll"); //声明所用到的dll文件
//判断是否正确加载
if (mylib.load())
{
std::cout << "DLL loaded!"<<std::endl;
CreatDll creatDll = (CreatDll)mylib.resolve("getDllObject");
ReleseDll decDll=(ReleseDll)mylib.resolve ("releseDllObject");
fun hello=(fun)mylib.resolve ("helloWorld");
if(hello)hello();
if(creatDll&&decDll)
{
Dll *testDll = creatDll();
testDll->GetStrAdd ("abc","ABD");
testDll->Print ();
decDll(testDll);
}
}
//加载失败
else
std::cout << "DLL is not loaded!"<<std::endl;
mylib.unload ();
return a.exec();
}
工程文件加入
#LIBS += "D:/qt_work/build-dllTest-Desktop_Qt_5_11_1_MinGW_32bit-Debug/debug/dll.dll" 或者
LIBS += D:qt_workuild-dllTest-Desktop_Qt_5_11_1_MinGW_32bit-Debugdebugdll.dll
否则会报错:
D:qt_workuild-dllTest-Desktop_Qt_5_11_1_MinGW_32bit-Debugdebugmain.o:-1: In function
`Z5qMainiPPc':
D:qt_workdllTestmain.cpp:30: error: undefined reference to
`_imp___ZN3Dll9GetStrAddENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_'
D:qt_workdllTestmain.cpp:31: error: undefined reference to `_imp___ZN3Dll5PrintEv'