std::string 转为 LPCTSTR类型

在串口通讯中使用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提示框,可注释
    MessageBox(NULL, lpctstr, TEXT("MessageBox Title"), MB_OK);
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值