.NET System::String to ANSI char*

Friday March 2ndC#, C++ Category

Hi All,

I’ve been doing a bit of work of late dealing with interops between managed and unmanaged code, and I have nailed a little snippet which shows how convert between a managed .NET String object and a stanard ANSI/C-style string. Check out the following code if you need to do the same:

[source:cpp]System::String managedString = WHATEVER;
System::IntPtr stringPtr = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi( myString );
char* unmanagedString = static_cast< char* >( stringPtr.ToPointer() );
// do whatever you want with the unmanaged string …
CallReallyOldCFunction( unManagedString );
System::Runtime::InteropServices::Marshal::FreeHGlobal( stringPtr );[/source]Another option is to use the CString class, but some people might not want to have to deal with the extra overhead or objects. The choice is yours :)

No Comments Yet

You can be the first to comment!

Leave a comment

Size

Colors