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::StringToHGlobalAn si(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.
}
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::StringToHGlobalAn
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.
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
String* s10 = S"char ptr";
const __wchar_t __pin* sp = PtrToStringChars(s10);
char* sChar = (char*)(void*)System::Runt
std::cout << sChar << std::endl;
System::Runtime::InteropSe
I don't remember why it is written by such way, but it works.