cannot convert 'const char*' to 'LPCWSTR {aka const wchar_t*}'

前端 未结 4 1881
孤独总比滥情好
孤独总比滥情好 2020-12-06 12:03

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          


        
4条回答
  •  醉梦人生
    2020-12-06 12:28

    The Windows CreateFile function is actually a macro that expands to one of:

    • CreateFileA, which takes a file path of type const char*
    • CreateFileW, which takes a file path of type const wchar_t*.

    (The same is true for most of the functions in the Windows API that take a string.)

    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.

    Your options are to:

    1. Change the function parameter to a UTF-16 (const wchar_t*) string.
    2. Keep the char* parameter, but have your function explicitly convert it to a UTF-16 string with a function like MultiByteToWideChar.
    3. Explicitly call CreateFileA instead of CreateFile.
    4. Compile your program without UNICODE, so that the macros expand to the A versions by default.
    5. 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.

    Edit: I don't know if a kidnapping was involved, but Windows 10 1903 finally added support for UTF-8 as an ANSI code page.

提交回复
热议问题