我正在尝试设置一个 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,但有两个不同的函数:CreateFileA
和CreateFileW
。前者采用 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
并选择“使用多字节字符集”,如下截图所示:
关于c++ - Visual Studio 2010 Arduino cpp 错误 : argument of type "char *" is incompatible with parameter of type "LPCWSTR",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805621/