2023年12月3日发(作者:)
QT加载第三方库
一、 (动态)显示加载(只需要.dll,不需要.lib/.h)
A) 将.dll放到编译目录下,例如:build-TestLoadDll-Desktop_Qt_5_5_0_MinGW_32bit-Debug
B) 包含
#include
C) 在Windows下程序显示调用dll的步骤分为三步(三个函数):LoadLibrary()、GetProcAdress()、FreeLibrary()
第一步:QLibrary mylib(""); //声明所用到的dll文件
第二步:判断dll是否加载成功if(())
第三步:e("DC_init_comm") //援引DC_init_comm()函数
第四步:卸载库 ();
void MainWindow::on_pushButton_clicked() //开启设备
{
typedef long (*Fun)(const char *,unsigned long);
QLibrary mylib(""); //声明所用到的dll文件
long result;
if (()) //判断是否正确加载
{
QMessageBox::information(NULL,"OK","DLL load is OK!");
Fun open=(Fun)e("DC_init_comm"); //援引 DC_init_comm() 函数
if (open)
//是否成功连接上DC_init_comm()函数
{
//QMessageBox::information(NULL,"OK","Link to Function is OK!");
result=open("COM1",115200);
//函数指针调用dll中的 DC_init_comm() 函数
QMessageBox::information(NULL,"OK",QString::number(result,10));
//如果返回数小于0则通讯失败 这里返回-1
();//卸载库
}
else
QMessageBox::information(NULL,"NO","Linke to Function is not OK!!!!");
}
else
QMessageBox::information(NULL,"NO","DLL is not loaded!");
}
二、 (静态)隐式加载(需要.lib/.h/.dll)
1、首先我们把 .h 与 .lib文件复制到程序当前目录下,然后再把dll文件复制到程序的debug目录.
2、下面我们在pro文件中,添加 .lib 文件的位置(MingGW 32bit版):
LIBS += ./debug/
3、在工程中包含.h文件 #include “Trf32.h”,如果是c版的 要加上
extern "C" __declspec(dllimport) int __stdcall DC_init_comm (const char*, unsigned long);
4、在程序中调用dll 中相关函数。result=DC_exit_comm(result);
void MainWindow::on_pushButton_2_clicked()//关闭设备
{
long result=DC_init_comm("COM1",115200);
//函数指针调用dll中的 DC_init_comm() 函数
QMessageBox::information(NULL,"OK",QString::number(result,10));
if(result>=0)
{
result=DC_exit_comm(result);
QMessageBox::information(NULL,"OK",QString::number(result,10));
//小于0则关闭失败
}
}
void MainWindow::on_pushButton_3_clicked() //蜂鸣
{
long result = DC_init_comm("COM1",115200);
long flag = dc_beep(result,10);
if(flag<0)
QMessageBox::information(NULL,"OK","Beep failed!");
result=DC_exit_comm(result);
QMessageBox::information(NULL,"OK",QString::number(result,10));
//小于0则关闭失败
}
VC静态调用dll方法
1.把你的拷到你目标工程(需调用的工程)的Debug目录下;
2.把你的拷到你目标工程(需调用的工程)目录下;
3.把你的Trf32.h(包含输出函数的定义)拷到你目标工程(需调用的工程)目录下;
4.打开你的目标工程选中工程,选择Visual C++的Project主菜单的Settings菜单;
5.执行第4步后,VC将会弹出一个对话框,在对话框的多页显示控件中选择Link页。然后在Object/library modules输入框中输入:
6.选择你的目标工程Head Files加入:Trf32.h文件;
7.最后在你目标工程(*.cpp,需要调用DLL中的函数)中包含你的:#include"Trf32.h"
动态调用其程序如下:
动态调用时只需做静态调用步骤1.
{
HINSTANCE hDllInst = LoadLibrary("");
if(hDllInst)
{
typedef DWORD (WINAPI *MYFUNC)(DWORD,DWORD);
MYFUNC youFuntionNameAlias = NULL; // youFuntionNameAlias 函数别名
youFuntionNameAlias = (MYFUNC)GetProcAddress
(hDllInst,"youFuntionName");// youFuntionName 在DLL中声明的函数名
if(youFuntionNameAlias)
youFuntionNameAlias(param1,param2);
FreeLibrary(hDllInst); }
}
T10 2040
D8 2040
T8 2040


发布评论