欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt调用dll

程序员文章站 2022-06-03 20:52:34
...

直接上代码

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_work\build-dllTest-Desktop_Qt_5_11_1_MinGW_32bit-Debug\debug\dll.dll

否则会报错:

D:\qt_work\build-dllTest-Desktop_Qt_5_11_1_MinGW_32bit-Debug\debug\main.o:-1: In function
  `Z5qMainiPPc':
D:\qt_work\dllTest\main.cpp:30: error: undefined reference to
  `_imp___ZN3Dll9GetStrAddENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_'
D:\qt_work\dllTest\main.cpp:31: error: undefined reference to `_imp___ZN3Dll5PrintEv'
相关标签: Qt调用dll Qt