QT学习之动态加载DLL

QT动态加载32位DLL,要加载的工程也得是32位的才行,不然QLibrary加载动态库失败;
特别要注意动态库的约定:参考此贴https://blog.youkuaiyun.com/qq_36568418/article/details/100540150
如:dll是__stdcall的,在加载动态库接口时要指明是此约定的接口,如:typedef int (
__stdcall** SDT_ResetSAM)(int, int); // 复位*
如下,先设置扩展-》QT VS Tool选择MSVC是32位的,新建工程时默认勾选的就是32位的设置;
在这里插入图片描述
加载比较简单:
cpp文件如下:

QString m_strLibPath;   //动态库路径
m_strLibPath = "sdtapi.dll"; // 和工具在同一目录
m_pLib = new QLibrary(m_strLibPath);
if (!m_pLib->load()) {
    traceLog.outPutMsg(QtDebugMsg, "load faild");
    QMessageBox::about(this, title, QString::fromUtf8("加载动态库sdtapi.dll失败"));
}
if (!resolveFunction(openPort, "SDT_OpenPort")) {
    QMessageBox::about(this, title, QString::fromUtf8("加载动态库函数SDT_OpenPort失败"));
}

使用:
int ret = openPort(5);

.h文件如下:

typedef int (*SDT_OpenPort)(int); // 打开串口或U口 声明一个函数指针

调用类中定义如下lamda用来找的具体dll中的接口
//调用dll的resolve功能函数
template<typename Func>
bool resolveFunction(Func& f, const char* name) {
    f = (Func)m_pLib->resolve(name);    //把名为nanme的功能函数指针传递给对象功能函数f
    if (nullptr == f) {
        qDebug() << "resolve function " << name << "failed";
        return false;
    }
    qDebug() << "resolve function " << name << "success";
    return true;
}

SDT_OpenPort openPort;  定义一个函数对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值