Link to home
Start Free TrialLog in
Avatar of VPitre
VPitre

asked on

converting a System::String to a c++ char array

I have a managed type of String str. I want to convert it into a C++ style char* and copy it into str1. I am using VC++.Net.

I use the following code. The str1 gets converted to const char* str2 but I get a null exception
when I try to copy the const char* str2 to char* str1. What do I need to do to get this code running? Please help.. Thank you.

//to convert a String* to char*            

char* str1 = "";

      
try {
IntPtr ptr = Marshal::StringToHGlobalAnsi(str);
const char *str2 = static_cast<const char*>(ptr.ToPointer());
            
strcpy(str1, str2); //this is the problem
            
Marshal::FreeHGlobal(ptr);
}
catch (System::Exception *x) {
// StringToHGlobalAnsi() failed.
}
Avatar of AlexFM
AlexFM

This is one of my mixed programming exersizes:

    String* s10 = S"char ptr";
    const __wchar_t __pin* sp = PtrToStringChars(s10);
    char* sChar = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(s10);

    std::cout << sChar << std::endl;

    System::Runtime::InteropServices::Marshal::FreeHGlobal(sChar);

I don't remember why it is written by such way, but it works.
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial