c++ - Visual Studio 2010 Arduino cpp 错误 : argument of type "char *" is incompatible with parameter of type "LPCWSTR"

标签 c++ visual-studio arduino tchar lpcwstr

我正在尝试设置一个 arduino uno 用于与 visual studio 2010 中的 C++ 程序进行串行端口通信。我正在使用此处找到的代码:http://playground.arduino.cc/Interfacing/CPPWindows

不幸的是,.cpp 文件在第 9 行为变量“portName”提供了以下消息:

错误:“char *”类型的参数与“LPCWSTR”类型的参数不兼容

我不明白这个错误消息,并尝试了一些不同的方法来修复它。任何帮助将不胜感激!

最佳答案

鉴于您问题中的代码链接,问题似乎出在这里:

Serial::Serial(char *portName)
{
    ...

    this->hSerial = CreateFile(portName,  // <--- ERROR

CreateFile is a Win32 API that expects an LPCTSTR as first string parameter .

LPCTSTR 是一个 Win32 typedef,它被扩展为:

  • const char* 在 ANSI/MBCS 构建中
  • const wchar_t* 在 Unicode 构建中(自 VS2005 以来一直是默认设置)

由于您使用的是 VS2010,您可能处于默认的 Unicode 构建模式。

实际上,没有公开“物理”CreateFile API,但有两个不同的函数:CreateFileACreateFileW。前者采用 const char* 输入字符串,后者采用 const wchar_t*

在 Unicode 构建中,CreateFile 是扩展为 CreateFileW 的预处理器宏;在 ANSI/MBCS 构建中,CreateFile 被扩展为 CreateFileA

因此,如果您处于 Unicode 构建模式,您的 CreateFile 调用将扩展为 CreateFileW(const wchar_t*, ...)。由于 portName 被定义为 char*,因此 wchar_t*char* 之间存在不匹配,您得到一个编译器错误。

要解决这个问题,您有一些选择。

例如,您可以在代码中显式调用 CreateFileA() 而不是 CreateFile()。这样,您将使用该函数的 ANSI/MBCS 版本(即采用 const char* 的函数),独立于 Visual Studio 中的实际 ANSI/MBCS/Unicode 设置。


另一种选择是将您当前的build设置从默认的 Unicode 模式更改为 ANSI/MBCS。为此,您可以遵循以下路径:

Project Properties | Configuration Properties | General | Character Set

并选择“使用多字节字符集”,如下截图所示:

Setting Multi-Byte Character Set in VS2010 IDE

关于c++ - Visual Studio 2010 Arduino cpp 错误 : argument of type "char *" is incompatible with parameter of type "LPCWSTR",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805621/

相关文章:

c++ - 如何使用 IOCP 获取客户端真实 IP 地址和端口?

c - 为什么在visual studio C编译器中会抛出这个异常?

cgi - PySerial:创建串行对象而不打开端口

c - Arduino伺服结构 "does not name a type"

c++ - 在声明前使用静态常量成员

c++ - std::lists 的 std::vector 中的不可复制元素

visual-studio - MS VS 测试运行程序异常

android - 如何在 android 上以编程方式取消配对或删除配对的蓝牙设备?

c++ - "port"Visual Studio C++ 项目在 Linux 上编译的最简单方法?

c# - 如何从 .vcxproj 文件中获取所有项目宏及其值