创建QT中的一个DLL,如下图选择:
效果如图所示:
下面是代码:
dll.h::
#ifndef DLL_H
#define DLL_H
#include <string>
using namespace std;
#include "dll_global.h"
class DLLSHARED_EXPORT Dll
{
public :
Dll();
~Dll();
void Print();
string GetStrAdd(string str1, string str2);
};
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);
}
#endif // DLL_H
dll_global.h:
#ifndef DLL_GLOBAL_H
#define DLL_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(DLL_LIBRARY)
# define DLLSHARED_EXPORT Q_DECL_EXPORT
#else
# define DLLSHARED_EXPORT Q_DECL_IMPORT
#endif
#endif // DLL_GLOBAL_H
dll.cpp:
#include "dll.h"
#include <iostream>
Dll::Dll()
{
std::cout<< "New Dll Object !" <<endl;
}
Dll::~Dll()
{
std::cout<< "Dll Object Des~~" <<endl;
}
void Dll::Print ()
{
std::cout<< "Dll::Print !" <<endl;
}
string Dll::GetStrAdd (string str1, string str2)
{
string s=str1+str2;
std::cout<< "Dll::GetStrAdd->return->" <<s<<endl;
return (s);
}
void helloWorld()
{
std::cout << "GlobalFun->hello,world!" <<endl;
}
int add( int a, int b)
{
std::cout<< "GlobalFun->add->return->" <<(a+b)<<endl;
return a + b;
}
Dll* getDllObject()
{
return new Dll();
}
void releseDllObject(Dll* dll)
{
delete dll;
}
测试中的 mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
typedef Dll* (*pgetDllObject)(); //定义函数指针,获取类Dll对象;
typedef void (*preleseDllObject)(Dll*);
typedef void (*phelloWorld)();
void MainWindow::on_pushButton_clicked()
{
QLibrary dlllib( "dll.dll" ); //声明所用到的dll文件
if (dlllib.load())
{
std::cout << "DLL loaded!" <<std::endl;
pgetDllObject creatDll_func = (pgetDllObject)dlllib.resolve( "getDllObject" );
preleseDllObject decDll_func=(preleseDllObject)dlllib.resolve ( "releseDllObject" );
phelloWorld hello_func=(phelloWorld)dlllib.resolve( "helloWorld" );
if (hello_func)
hello_func();
if (creatDll_func&&decDll_func)
{
Dll *testDll = creatDll_func();
testDll->GetStrAdd( "abc" , "ABD" );
testDll->Print();
decDll_func(testDll);
}
}
else
std::cout << "DLL is not loaded!" <<std::endl;
// return a.exec();
dlllib.unload ();
}
或者下面的调用方法:void MainWindow::on_pushButton_clicked() { Dll *pdll1 = new Dll(); pdll1->GetStrAdd("aaa","bbb"); pdll1->Print(); delete pdll1; }
下面用静态的调用方法:
调用方法:把LIB和头文件放到调用方工程下面,然后代码如下:
void MainWindow::on_pushButton_clicked()
{
Dll2 *pdll2=new Dll2();
pdll2->prnt("xxx");
delete pdll2;
}