在串口通讯中使用CreateFile()时,第一个参数类型为 LPCTSTR,通常使用的string类型需要进行转换
HANDLE CreateFile(
LPCTSTR lpFileName, // 指向文件名的指针
DWORD dwDesiredAccess, // 访问模式(写 / 读)
DWORD dwShareMode, // 共享模式
LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 指向安全属性的指针
DWORD dwCreationDisposition, // 如何创建
DWORD dwFlagsAndAttributes, // 文件属性
HANDLE hTemplateFile // 用于复制文件句柄
);
// 假设有一个 std::string port_name
std::string port_name = "COM2";
// 将 std::string 转换为 std::wstring
std::wstring wideString(port_name.begin(), port_name.end());
// 获取 LPCTSTR 指针
#ifdef UNICODE
LPCTSTR lpctstr = wideString.c_str();
#else
// 将 wideString 转换为 const char* 如果不是 Unicode 环境
const char* narrowCString = port_name.c_str();
LPCTSTR lpctstr = narrowCString;
#endif
// 传递给 Windows API 函数进行转换,lpctstr类型即为 LPCTSTR
MessageBox(NULL, lpctstr, _T("MessageBox Title"), MB_OK);