How to convert String^ to char array
Solution 1
Your best bet is to follow the examples set forth in this question.
Here's some sample code:
String^ test = L"I am a .Net string of type System::String";
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(test);
char* nativeString = static_cast<char*>(ptrToNativeString.ToPointer());
The reason for this is because a .Net string is obviously a GC'd object that's part of the Common Language Runtime, and you need to cross the CLI boundary by employing the InteropServices boundary. Best of luck.
Solution 2
In C/C++ there is equivalence between char[] and char* : at runtime char[] is no more than a char* pointer to the first element of the array.
So you can use you char* where a char[] is expected :
#include <iostream>
using namespace System;
using namespace System::Runtime::InteropServices;
void display(char s[])
{
std::cout << s << std::endl;
}
int main()
{
String^ test = L"I am a .Net string of type System::String";
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(test);
char* nativeString = static_cast<char*>(ptrToNativeString.ToPointer());
display(nativeString);
}
So I think you can accept Maurice's answer :)
user1869623
Updated on December 03, 2020Comments
-
user1869623 over 3 years
Possible Duplicate:
Need to convert String^ to char *I have been looking so long for this solution but I can't find nothing specific. I work in Visual Studio C++, windows forms app. I need to convert
String^
value into char array. I have stored value fromTextBox
inString^
:String^ target_str = targetTextBox->Text; // lets say that input is "Need this string"
I need to convert this
String^
and get output similar to this:char target[] = "Need this string";
If it is defined as
char target[]
it works but I want to get this value fromTextBox
.I have tried marshaling but it didn't work. Is there any solution how to do this?
I have found how to convert
std::string
tochar
array so another way how to solve this is to convertString^
tostd::string
but I have got problems with this too.