Convert a managed string to an unmanaged string

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?
 
T

Tomas Restrepo \(MVP\)

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top