QT调用vs2019生成的c++动态库
dll库的创建方法:
VS2019创建c++动态链接库dll与调用方法-CSDN博客
加减法示范:
头文件
// 下列 ifdef 块是创建使从 DLL 导出更简单的
// 宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 DLL3_EXPORTS
// 符号编译的。在使用此 DLL 的
// 任何项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将
// DLL3_API 函数视为是从 DLL 导入的,而此 DLL 则将用此宏定义的
// 符号视为是被导出的。
#ifdef DLL3_EXPORTS
#define DLL3_API __declspec(dllexport)
#else
#define DLL3_API __declspec(dllimport)
#endif
// 此类是从 dll 导出的
class DLL3_API CDll3 {
public:
CDll3(void);
int name;
int age;
// TODO: 在此处添加方法。
};
extern DLL3_API int nDll3;
extern DLL3_API CDll3;
extern "C"
{
DLL3_API int fnDll3(void);
DLL3_API int fnAdd(int a, int b);
DLL3_API int fnSub(int a, int b);
}
cpp
// Dll3.cpp : 定义 DLL 的导出函数。
//
#include "pch.h"
#include "framework.h"
#include "Dll3.h"
// 这是导出变量的一个示例
DLL3_API int nDll3=666666;
// 这是导出函数的一个示例。
DLL3_API int fnDll3(void)
{
return 666;
}
DLL3_API int fnAdd(int a, int b)
{
return a + b;
}
DLL3_API int fnSub(int a, int b)
{
return a - b;
}
// 这是已导出类的构造函数。
CDll3::CDll3()
{
return;
}
每次修改后:都执行-》重新生成,确保 dll和lib文件的同步更新

记得 选择release,x64

把头文件.h与dll,lib放在一个地方以便拷贝到QT项目

编写正确,才能被QT调用:
使用dll查看工具显示fnAdd,fnSub编译正确

如果显示_cdecl fnAdd(int,int),则不能被调用。


QT创建一个项目:

把头文件.h与dll,lib拷贝到项目文件夹里面

构建编译:

查看默认编译后的路径:
拷贝到lib,和dll到exe生成的目录

QT显式调用dll
cpp主文件添加头文件:

构造函数添加代码:

dll隐式调用
pro文件添加:修改Dll3, Dll3表示Dll3.lib

就可以直接调用了:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLibrary>
#include <iostream>
#include <QMessageBox>
#include "Dll3.h"
#include <QDebug>
typedef int ( *pAdd)(int , int); //定义函数指针
using namespace std;
//using namespace MathFunc;
//extern "C" __declspec(dllexport) int fnAdd(int a, int b);
//extern "C" __declspec(dllexport) int fnAdd(int a, int b);
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//dll隐式调用
int cc = fnAdd(2,6);
qDebug()<<"cc value is :"<<QString::number(cc);
int cc_sub = fnSub(2,6);
qDebug()<<"cc_sub value is :"<<QString::number(cc_sub);
int n_dll3 = nDll3;
qDebug()<<"n_dll3 value is :"<<QString::number(n_dll3);
CDll3 aa;
aa.age =13;
CDll3 bb;
bb.age =15;
qDebug()<<"aa.age value is :"<<QString::number(aa.age);
qDebug()<<"bb.age value is :"<<QString::number(bb.age);
// 显示调用dll
// QLibrary mydll("Dll3.dll"); //与exe相同目录
// mydll.load();
// if(mydll.isLoaded())
// {
// pAdd add = (pAdd)mydll.resolve("fnAdd");
// if(add)
// {
// int ret = add(1,7); //在 这里调用DLL里的函数
// QMessageBox::information(this,"value","get_value is: "+QString::number(ret));
// cout<< ret << endl ;
// }
// add = (pAdd)mydll.resolve("fnSub");
// if(add)
// {
// int ret = add(9,7); //在 这里调用DLL里的函数
// QMessageBox::information(this,"value","get_value is: "+QString::number(ret));
// cout<< ret << endl ;
// }
// mydll.unload();
// }
}
MainWindow::~MainWindow()
{
delete ui;
}