How do I convert from std::wstring _TCHAR []?
-
09-10-2019 - |
Pergunta
I'm using a library and sends me std::wstring
from one of its functions, and another library that requires _TCHAR []
to be sent to it. How can I convert it?
Solução
Assuming you're using Unicode build, std::wstring.c_str() is what you need. Note that c_str() guarantees that the string it returns is null-terminated.
e.g.
void func(const wchar_t str[])
{
}
std::wstring src;
func(src.c_str());
If you're using non-Unicode build, you'll need to convert the Unicode string to non Unicode string via WideCharToMultiByte.
Outras dicas
As @Zach Saw said, if you build only for Unicode you can get away with std::wstring.c_str()
, but conteptually it would be better to define a tstring
(a typedef
for std::basic_string<TCHAR>
) so you can safely use this kind of string flawlessly with all the Windows and library functions which expect TCHAR
s1.
For additional fun you should define also all the other string-related C++ facilities for TCHAR
s, and create conversion functions std::string
/std::wstring
<=> tstring
.
Fortunately, this work has already been done; see here and here.
- Actually no compiled library function can really expect a
TCHAR *
, sinceTCHAR
s are resolved aschar
s orwchar_t
s at compile time, but you got the idea.
Use the ATL and MFC String Conversion Macros. This works regardless of whether you are compiling in _UNICODE
or ANSI mode.
You can use these macros even if you aren’t using MFC. Just include the two ATL headers shown in this example:
#include <string>
#include <Windows.h>
#include <AtlBase.h>
#include <AtlConv.h>
int main()
{
std::wstring myString = L"Hello, World!";
// Here is an ATL string conversion macro:
CW2T pszT(myString.c_str());
// pszT is now an object which can be used anywhere a `const TCHAR*`
// is required. For example:
::MessageBox(NULL, pszT, _T("Test MessageBox"), MB_OK);
return 0;
}