C++如何根据厂家提供的DLL库调用库中方法操作硬件?
一、DLL是什么?
动态链接库(Dynamic Link Library)DLL文件与EXE文件一样也是可执行文件,但是DLL也被称之为库,因为里面封装了各种类啊,函数啊之类的东西,就像是一个库一样,存储着很多东西,主要是用来调用的。
二、调用方式
调用方式主要分为两种:隐式(通过lib文件与头文件) 与 显式(只通过DLL文件)。
三、调用方法
隐式调用:
//将lib文件及头文件导入的项目中,并通过头文件调用库中的函数
配置参考链接:https://zhuanlan.zhihu.com/p/490440768
显示调用:
HMODULE hMod = LoadLibraryA("POS_SDK.dll");//载入动态库
FreeLibrary(hMod);//卸载函数库
四、实践操作
```cpp
#include <iostream>
#include <windows.h>
#include <string.h>
#include "test.h"
#define char TCHAR
#define _AFXDLL
using namespace std;
/*
根据厂家提供的开发文档调用对应函数接口,如何没有文档可以使用工具查看动态库中的函数功能。
*/
typedef long(*POS_Port_OpenA)(LPSTR szName, INT iPort, BOOL bFile, LPSTR szFilePath);
typedef long(*POS_Output_PrintFontStringA)(LONG iPrinterID, INT iFont, INT iThick, INT iWidth, INT iHeight,
INT iUnderLine, LPCSTR lpString);
using namespace std;
int testDell()
{
cout << "------------Dell库调用练习测试程序------------" << endl;
HMODULE hMod = LoadLibraryA("POS_SDK.dll");
if (hMod != NULL) {
POS_Port_OpenA posfunc;
posfunc = (POS_Port_OpenA)GetProcAddress(hMod, "POS_Port_OpenA");
if (posfunc != NULL) {
cout << "========找到对应的函数,即将开始调用函数===========" << endl;
char cmd[1000] = "COM8:115200, N, 8, 1";
long result = posfunc(cmd, 1000, FALSE, NULL);
cout << "获取的设备ID号码为:" << result << endl;
if (result < 0) {
cout << "串口打开失败,请检查串口号是否准确" << endl;
}
else
{
cout << "串口打开成功,可以正常操作凭条打印机" << endl;
POS_Output_PrintFontStringA stringfunc;
stringfunc = (POS_Output_PrintFontStringA)GetProcAddress(hMod, "POS_Output_PrintFontStringA");
if (stringfunc != NULL) {
cout << "成功:凭条打印机字符串打印接口查询接口找到了" << endl;
stringfunc(result, 0, 0, 0, 0, 0, "Hi, thank you for choosing our printer");
}
else
{
cout << "失败:凭条打印机字符串打印接口没有找到了" << endl;
}
}
}
else
{
cout << "未找到该函数,可能是函数名字错误请检查!" << endl;
}
FreeLibrary(hMod);
}
else
{
cout << "没有打开指定的DLL库,请检查!" << endl;
}
return 1;
}