Converting std::string to LPCSTR and LPWSTR
In C , it is sometimes necessary to convert a std::string to LPCSTR or LPWSTR for use with certain APIs. This can be achieved using the c_str() method.
Converting to LPCSTR
To convert a std::string to LPCSTR (a pointer to a constant null-terminated character array), simply use the c_str() method:
<code class="cpp">std::string str = "Hello, world!"; LPCSTR lpcstr = str.c_str();</code>
Converting to LPWSTR
Converting to LPWSTR (a pointer to a constant wide-character array) is slightly more complex as it requires using the WCHAR type:
<code class="cpp">std::string str = "Hello, world!"; size_t length = str.length(); WCHAR* buffer = new WCHAR[length + 1]; MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer, (int)length); LPWSTR lpwstr = buffer;</code>
Understanding LPCSTR, LPSTR, LPWSTR, and LPCWSTR
These acronyms stand for:
In general, LPCSTR and LPCWSTR are used with constant strings, while LPSTR and LPWSTR are used with mutable strings. Note that the "L" in these names is a legacy from 16-bit Windows and can be ignored.
The above is the detailed content of How to Convert std::string to LPCSTR and LPWSTR in C ?. For more information, please follow other related articles on the PHP Chinese website!