简体   繁体   中英

How do I convert from std::wstring _TCHAR []?

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?

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.

eg

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 .

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 s 1 .

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 .


  1. Actually no compiled library function can really expect a TCHAR * , since TCHAR s are resolved as char s or wchar_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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM