MC++ FAQ
Sunday 06 | 30 | 2002
Converting Strings
Several ways of converting between Managed System::String instances and C/C++ strings.

MC++ provides no direct way of converting between managed strings and unmanaged C/C++ strings and character arrays, so you have to do it yourself. The easiest way to do this is using the helper methods in the Marshal class found in the System::Runtime::InteropServices namespace.

To convert from a System::String* to a C-style char*, you can use one of the StringToHGlobalXXX methods, which allow you to convert to both ANSI and Unicode variants. There are also several other methods that allow you to convert to BSTRs, for example.

Here's an example of this:

using namespace System::Runtime::InteropServices;
const char* str = (const char*)
   (Marshal::StringToHGlobalAnsi(managedString)).ToPointer();
// use str as you wish or copy it elsewhere
// free string
Marshal::FreeHGlobal(IntPtr((void*)str));

To do the conversion the other way, use the PtrToStringXXX() methods instead.

Now, if you prefer to use the Standard C++ Library string classes instead, you can write simple wrapper methods to make the conversion easier. Here's an example of them:

void MarshalString ( System::String* s, std::string& os )
{
   using namespace System::Runtime::InteropServices;
   const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}
void MarshalString ( System::String* s, std::wstring& os )
{
   using namespace System::Runtime::InteropServices;
   const wchar_t* chars = 
      (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}
Posted by tomasr at June 30, 2002 11:37 PM
Comments

This was very helpful.

Thank you very much.

Scott Newland

Posted by: Scott Newland on August 4, 2003 03:16 PM

Thank you very much, very helpfull indeed

Leo

Posted by: Leo on August 6, 2003 12:08 PM

I probably could have used HOURS to figure this out :) luckily google pointed me to this...

Posted by: Peter Boner on October 2, 2003 02:38 PM

save me hell lot of time!!thanks!

Posted by: Ben Chan on November 14, 2003 07:23 AM

I am able to get this code working in a console app but not an empty managed c++ class. Does someone have any idea what I am doing wrong. When I include the std string header into my project and try to compile, I get the following errors:

stringtest2 error LNK2020: unresolved token (0A000013) _CxxThrowException

stringtest2 error LNK2020: unresolved token (0A00002A) delete

stringtest2 fatal error LNK1120: 2 unresolved externals

Posted by: Kai on November 27, 2003 12:37 AM
Post a comment
Name:


Email Address:


URL:


Comments:


Remember info?

Copyright(C) 2002, Tomas Restrepo, All rights reserved. Powered by Movable Type 2.63