Convert a managed string to an unmanaged string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

HI
In keeping with my policy of always using _TCHAR*s when possible, I am
trying to convert a System::String* to a _TCHAR*.
When I use this (my eventual aim is to get it into a pre-allocated,
unmanaged, _TCHAR* called 'error'):
const _TCHAR* umstring = (const
_TCHAR*)Marshal::StringToHGlobalAuto(merror).ToPointer();
_tcscpy(error, umstring);
Marshal::FreeHGlobal(IntPtr((void*)umstring));

then 'error' only receives the first character of the System::String*.

But when I do

const char* umstring = (const
char*)Marshal::StringToHGlobalAnsi(merror).ToPointer();
_tcscpy(error, umstring);
Marshal::FreeHGlobal(IntPtr((void*)umstring));

it gets it all OK.
Why can't I do it with _TCHAR*s?
 
Bonj,
In keeping with my policy of always using _TCHAR*s when possible, I am
trying to convert a System::String* to a _TCHAR*.
When I use this (my eventual aim is to get it into a pre-allocated,
unmanaged, _TCHAR* called 'error'):
const _TCHAR* umstring = (const
_TCHAR*)Marshal::StringToHGlobalAuto(merror).ToPointer();
_tcscpy(error, umstring);
Marshal::FreeHGlobal(IntPtr((void*)umstring));

then 'error' only receives the first character of the System::String*.

But when I do

const char* umstring = (const
char*)Marshal::StringToHGlobalAnsi(merror).ToPointer();
_tcscpy(error, umstring);
Marshal::FreeHGlobal(IntPtr((void*)umstring));

it gets it all OK.
Why can't I do it with _TCHAR*s?

StringToHGlobalAuto() isn't like the _tcs CRT apis... it has no clue about
_UNICODE/_MBCS definitions, since it is just a real .NET API. In practice,
it is fairly useful, since whether it returns unicode or ansi strings
depends on the runtime platform (i.e. the OS), and cannot be controlled at
compile time.

Hence, you'll need to add your own #ifdef guard around and call
StringToHGlobalAnsi or StringToHGlobalUni as appropriate.
 
Back
Top