这个问题在这里已经有了答案:
9年前关闭。
Possible Duplicate:
Need to convert String^ to char *
我一直在寻找这个解决方案,但我找不到任何具体的东西。我在 Visual Studio C++、Windows 窗体应用程序中工作。我需要转换
String^
值转换为 char 数组。我存储了
TextBox
的值在 String^
:String^ target_str = targetTextBox->Text;
// lets say that input is "Need this string"
我需要转换这个
String^
并获得与此类似的输出:char target[] = "Need this string";
如果定义为
char target[]
它有效,但我想从 TextBox
获取此值.我尝试过编码,但没有奏效。有什么解决方案如何做到这一点?
我找到了如何转换
std::string
至char
数组所以另一种解决方法是转换 String^
至std::string
但我也有这个问题。
最佳答案
最好的办法是遵循 this question 中列出的示例。 .
这是一些示例代码:
String^ test = L"I am a .Net string of type System::String";
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(test);
char* nativeString = static_cast<char*>(ptrToNativeString.ToPointer());
这是因为 .Net 字符串显然是一个 GC 处理的对象,它是公共(public)语言运行时的一部分,您需要通过使用 InteropServices 边界来跨越 CLI 边界。祝你好运。
关于string - 如何将 String^ 转换为 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665649/