Study/C++

How to convert std::string to TCHAR*

붕대마음 2011. 1. 6. 17:05
반응형

How to convert std::string to TCHAR*

Most of the time people used to get this error , cannot convert std::string to TCHAR*
Here is the code snippet which will convert std::string to TCHAR* and vice verse

 
typedef std::basic_string<TCHAR> tstring;  
 
TCHAR* StringToTCHAR(string& s)
{
  tstring tstr;
  const char* all = s.c_str();
  int len = 1 + strlen(all);
  wchar_t* t = new wchar_t[len]; 
  if (NULL == t) throw std::bad_alloc();
  mbstowcs(t, all, len);
  return (TCHAR*)t;
}
 
std::string TCHARToString(const TCHAR* ptsz)
{
     int len = wcslen((wchar_t*)ptsz);
     char* psz = new char[2*len + 1];
     wcstombs(psz, (wchar_t*)ptsz, 2*len + 1);
     std::string s = psz;
     delete [] psz;
     return s;
}

link : http://ukanth.in/blog/?p=180