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?

Foi útil?

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 TCHARs1.

For additional fun you should define also all the other string-related C++ facilities for TCHARs, and create conversion functions std::string/std::wstring <=> tstring.

Fortunately, this work has already been done; see here and here.


  1. Actually no compiled library function can really expect a TCHAR *, since TCHARs are resolved as chars or wchar_ts 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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top