October 18, 2004

Convert from System::String* to TCHAR*/CString

The conversion from System::String* to TCHAR*/CString is not directly supported. You can either convert to Unicode or Ansi (What is an ANSI string?).

To support TCHAR you have to do:

//#include <vcclr.h> System::String *mstr = S"Hello world"; TCHAR *ustr; #ifdef _UNICODE ustr = new TCHAR[mstr->get_Length()+1]; const __wchar_t __pin * umstring = PtrToStringChars(mstr); #else const char* umstring = (const char*)Marshal::StringToHGlobalAnsi(mstr).ToPointer(); ustr = new TCHAR[strlen(umstring)+1]; #endif _tcscpy(ustr, umstring); #ifndef _UNICODE Marshal::FreeHGlobal(IntPtr((void*)umstring)); #endif // do something with the unmanaged string delete [] ustr;

To support CString:

System::String *mstr = S"Hello world"; CString dest(mstr); // do something with the unmanaged string

Links: HOW TO: Convert from System::String* to Char* in Visual C++ .NET


Posted 3 years, 3 months ago on October 18, 2004
The trackback url for this post is http://blog.kalmbachnet.de/bblog/trackback.php/18/

Comments have now been turned off for this post