Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / Managed C++ / October 2004

Tip: Looking for answers? Try searching our database.

Convert a managed string to an unmanaged string

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Bonj - 09 Oct 2004 20:55 GMT
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?
Tomas Restrepo \(MVP\) - 09 Oct 2004 22:50 GMT
Bonj,

> In keeping with my policy of always using _TCHAR*s when possible, I am
> trying to convert a System::String* to a _TCHAR*.
[quoted text clipped - 16 lines]
> 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.

Signature

Tomas Restrepo
tomasr@mvps.org


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.