qt调用vs纯虚函数的dll


#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();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值