QT动态加载32位DLL,要加载的工程也得是32位的才行,不然QLibrary加载动态库失败;
特别要注意动态库的约定:参考此贴https://blog.csdn.net/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; 定义一个函数对象