QT创建与调用Dll方法

创建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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值