問題描述
我在我的 C++ 代碼中遇到一個我無法理解的錯誤.精簡后的代碼位在這里:
I'm getting an error in my C++ code that I can't quite make sense of. The stripped down code bits are here:
RS232Handle=OpenRS232("COM1", 9600);
HANDLE OpenRS232(const char* ComName, DWORD BaudRate)
{
ComHandle=CreateFile(ComName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
}
我收到以下錯誤:
error: cannot convert 'const char*' to 'LPCWSTR {aka const wchar_t*}' for argument '1' to 'void* CreateFileW(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE)'
ComHandle=CreateFile(ComName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
代碼取自 VS 代碼,我現在使用 Qt creator.
The code was taken from VS code and I am now using Qt creator.
我該如何解決這個問題?謝謝!
How can I fix this issue? Thanks!
推薦答案
Windows CreateFile 函數實際上是一個擴展為以下之一的宏:
The Windows CreateFile function is actually a macro that expands to one of:
CreateFileA
,它采用const char*
類型的文件路徑CreateFileW
,它采用const wchar_t*
類型的文件路徑.
CreateFileA
, which takes a file path of typeconst char*
CreateFileW
, which takes a file path of typeconst wchar_t*
.
(Windows API 中大多數采用字符串的函數也是如此.)
(The same is true for most of the functions in the Windows API that take a string.)
您聲明了參數 const char* ComName
,但顯然編譯時定義了 UNICODE
,因此它調用了 W
版本的功能.沒有從 const wchar_t*
到 const char*
的自動轉換,因此出現錯誤.
You're declaring the parameter const char* ComName
, but apparently compiling with UNICODE
defined, so it's calling the W
version of the function. There's no automatic conversion from const wchar_t*
to const char*
, hence the error.
您的選擇是:
- 將函數參數更改為 UTF-16 (
const wchar_t*
) 字符串. - 保留
char*
參數,但讓您的函數使用 MultiByteToWideChar. - 顯式調用
CreateFileA
而不是CreateFile
. - 在不使用
UNICODE
的情況下編譯您的程序,以便宏默認擴展為A
版本. - 綁架一位著名的 Microsoft 開發人員并強迫他閱讀UTF-8 Everywhere,直到他同意讓 Windows 完全支持 UTF-8 作為ANSI"代碼頁,從而使各地的 Windows 開發人員擺脫這種寬字符的束縛.
- Change the function parameter to a UTF-16 (
const wchar_t*
) string. - Keep the
char*
parameter, but have your function explicitly convert it to a UTF-16 string with a function like MultiByteToWideChar. - Explicitly call
CreateFileA
instead ofCreateFile
. - Compile your program without
UNICODE
, so that the macros expand to theA
versions by default. - Kidnap a prominent Microsoft developer and force him to read UTF-8 Everywhere until he agrees to have Windows fully support UTF-8 as an "ANSI" code page, thus freeing Windows developers everywhere from this wide-character stuff.
我不知道是否涉及綁架,但 Windows 10 1903 終于添加了支持 對于 UTF-8 作為 ANSI 代碼頁.
I don't know if a kidnapping was involved, but Windows 10 1903 finally added support for UTF-8 as an ANSI code page.
這篇關于無法將“const char*"轉換為“LPCWSTR {aka const wchar_t*}"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!