views:

57

answers:

2

I have a String^1 and I need to convert it to const char* and c_str() does not work as it is not a member of System::String. Is there a simpler way to do this other than this method? I am only doing this once and it is from an openFileDialog->Filename, so the input will not be anything complex. I am using Visual Studio 2008.
Thanks

+3  A: 

I think this page may help you.

Hope that helps

Patrice Bernassola
Wow, this is a lot more than I thought it was going to be. Thanks.
Nick S.
You're welcome Nick
Patrice Bernassola
A: 

The simplest way to convert a String^ to a plain char* string is to use just a bit of the code that you have linked to. The important part is:

pin_ptr<const wchar_t> wch = PtrToStringChars( source );

Once this is done you can use wch variable to access your characters, but there are a few warnings with this code.

  • If you are just going to use the wch variable to access the string then you must make sure that the lifetime of the string is less than the lifetime of the scope in which the pin_ptr is declared.
  • If you want to use the string elsewhere, or pass it to some longer lived function then you will need to extract out the contents and save that somewhere else. That is what most of the code in the example that you linked to is doing.

I would recommend saving that string in either a STL string (or wstring) class or at the very least copying the contents to a separately managed buffer - like the example is doing.

At work we use some overloaded functions which do conversions from one string type to another, all using the same name. The one that converts from a .Net string to a STL string is pretty much:

std::wstring ConvertString(String^ source)
{
    pin_ptr<const wchar_t> pinned_string_ptr(PtrToStringChars(source));
    return std::wstring(pinned_string_ptr);
}
Daemin