问题描述
我一直在寻找这么长的解决方案,但我找不到任何具体的。我在Visual Studio C ++,窗体窗体应用程序。我需要将 String ^
值转换为char数组。
我已存储来自中的
TextBox
的值 String ^
:
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 from TextBox
in String^
:
String^ target_str = targetTextBox->Text;
// lets say that input is "Need this string"
需要转换此 String ^
并获得类似于以下内容的输出:
I need to convert this String^
and get output similar to this:
char target[] = "Need this string";
如果定义为 char target []
它工作,但我想从 TextBox
。
If it is defined as char target[]
it works but I want to get this value from TextBox
.
得到这个值我已经尝试了编组,但它没有工作。是否有任何解决方案如何做到这一点?
I have tried marshaling but it didn't work. Is there any solution how to do this?
我已经找到如何将 std :: string
c $ c> char 数组,所以另一种方式如何解决这是转换 String ^
到 std :: string
但我也有这个问题。
I have found how to convert std::string
to char
array so another way how to solve this is to convert String^
to std::string
but I have got problems with this too.
推荐答案
最好的办法是遵循。
以下是一些示例代码:
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'd对象,公共语言运行时,并且您需要通过使用InteropServices边界跨过CLI边界。祝你好运。
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.
这篇关于如何将String ^转换为char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!