#include<iostream>
#include<string>
using namespace std;
#ifdef _EXPORTING
#define CLASS_DECLSPEC __declspec(dllexport)
#else
#define CLASS_DECLSPEC __declspec(dllimport)
#endif
class IPerson
{
public:
IPerson() {};
//接口
virtual void SetName(const string& strName) = 0;
virtual const string GetName() = 0;
virtual void Work() = 0;
};
Project1.h头文件定义了一个抽象类
.cpp
#include "Project1.h"
//定义接口
extern "C"
{
CLASS_DECLSPEC bool GetIPersonObject(void** _RtObject);
}
class CTeacher :public IPerson
{
public:
CTeacher() {}
//接口实现
void SetName(const string& strName);
const string GetName();
void Work();
private:
string m_strName;
};
void CTeacher::SetName(const string& strName)
{
m_strName = strName;
cout << "set name" << endl;
}
const string CTeacher::GetName()
{
cout << "get name" << endl;
return m_strName;
}
void CTeacher::Work()
{
printf("%s", "work");
}
bool GetIPersonObject(void** _RtObject)
{
IPerson* pMan = NULL;
pMan = new CTeacher();
*_RtObject = (void*)pMan;
cout << "create object" << endl;
return true;
}
在子类中重写函数,GetIPersonObject函数是导出函数在函数中创建子类。
生成DLL在,吧dll放到qt可执行文件夹目录里。
在qt里创建项目加入Project1.h
调用DLL
#include <QCoreApplication>
#include <windows.h>
#include <QDebug>
#include "Project1.h"
//定义函数指针
typedef bool(*lpAddFun)(void** object);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
HINSTANCE hDll;
lpAddFun addFun;
hDll = LoadLibrary(L"Project1.dll");
if (hDll != NULL)
{
addFun = (lpAddFun)GetProcAddress(hDll, "GetIPersonObject");/*用addFun取代dll库中的add函数*/
if (addFun != NULL)
{
IPerson *ip = NULL;
addFun((void**)&ip);//调用dll中的GetIPersonObject()函数
const std::string name = "tom";
ip->SetName(name);
qDebug()<<QString::fromStdString(ip->GetName());
ip->Work();
}
FreeLibrary(hDll);
}
return a.exec();
}