Converting System::String to char *

By saherneklawy

The official way to convert a visual c++ System::String to a char * could be found here. Such strings are everywhere in windows forms applications.

A simpler way (for people who are used to using standard c\c++) to do the conversion is as follows:

void string2charPtr(String ^orig, char *&out)
{
int length = orig->Length;
out = new char[length+1];
for(int i=0;i<length;i++)
out[i] = (char) orig[i];
out[length] = '';
}

Please feel free to comment on the function above.

Tags: , ,

2 Responses to “Converting System::String to char *”

  1. Abdallah El Guindy Says:

    If you don’t really want to change the C-string, you can use:

    String^ s;

    using namespace Runtime::InteropServices;
    const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();

  2. saherneklawy Says:

    But this is not really straight forward to people who are used to standard c.
    It is definitely better than options Microsoft suggest, if it works across Visual Studio versions

Leave a Reply