std::string to LPCTSTR

后端 未结 7 1240
甜味超标
甜味超标 2021-02-19 10:30

New version of the typical question of how to convert from std::string to LPCTSTR.

Reading from different SO posts I learnt that I should do th

7条回答
  •  有刺的猬
    2021-02-19 11:21

    The other explanations are correct:

    CreateDirectory, like many of the Window APIs, is actually a macro that expands to an "ANSI" or "Wide" version depending on whether UNICODE is defined. The ANSI version effectively converts the single-byte character string to a wide character string and then delegates to the wide character string version.

    However, the suggestions to call CreateDirectoryA directly come with some drawbacks:

    The conversions done by the "ANSI" APIs assume that the source string is encoded in the user's current code page. In simple cases, this is likely true. But in lots of real-life code, it's not. So you can end up with the wrong type of conversion, which leads to bugs you'll find much later. At least the bad typecast leads to bugs you find immediately.

    A better solution is to use wide strings (std::wstring) throughout, and to call CreateDirectoryW. No conversion to go wrong. No typecasts required.

    For many code bases, rewriting everything to use wide strings is not practical. It turns out that there are good reasons to do exactly the opposite and to continue to use std::strings but to standardize on having them hold UTF-8 text. Then, when you have to call a Windows API, you convert (not typecast) to UTF-16 and call the wide version of the API directly. That gives you full fidelity at the cost of a doing a few conversions and some temporary buffers. Since these types of calls are rarely in hot spots, the cost isn't usually a big deal.

    On Windows, to convert between UTF-8 and UTF-16, you can call MultiByteToWideChar/WideCharToMultiByte with the code page set to CP_UTF8.

提交回复
热议问题