String 如何将字符串^转换为字符数组

String 如何将字符串^转换为字符数组,string,visual-c++,c++-cli,type-conversion,String,Visual C++,C++ Cli,Type Conversion,可能重复: 我一直在寻找这个解决方案,但我找不到任何具体的。我在Visual StudioC++,Windows窗体应用程序中工作。我需要将String^值转换为char数组。 我已将TextBox中的值存储在String^中: String^ target_str = targetTextBox->Text; // lets say that input is "Need this string" 我需要转换此字符串^,并获得类似以下内容的输出: char target[] = "

可能重复:

我一直在寻找这个解决方案,但我找不到任何具体的。我在Visual StudioC++,Windows窗体应用程序中工作。我需要将
String^
值转换为char数组。 我已将
TextBox
中的值存储在
String^
中:

String^ target_str = targetTextBox->Text;

// lets say that input is "Need this string"
我需要转换此
字符串^
,并获得类似以下内容的输出:

char target[] = "Need this string";
如果它被定义为
char target[]
,它可以工作,但我想从
TextBox
获取这个值

我试过编组,但没用。有什么解决办法吗


我已经找到了如何将
std::string
转换为
char
数组的方法,所以解决这个问题的另一种方法是将
string^
转换为
std::string
,但我也遇到了一些问题

您最好的选择是遵循中列出的示例

下面是一些示例代码:

String^ test = L"I am a .Net string of type System::String";
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(test);
char* nativeString = static_cast<char*>(ptrToNativeString.ToPointer());
String^test=L“我是System::String类型的.Net字符串”;
IntPtr ptrToNativeString=Marshal::StringToHGlobalAnsi(测试);
char*nativeString=static_cast(ptrToNativeString.ToPointer());

这是因为.Net字符串显然是作为公共语言运行库一部分的GC对象,您需要通过使用InteropServices边界来跨越CLI边界。祝你好运。

在C/C++中,char[]和char*之间是等价的:在运行时,char[]只不过是指向数组第一个元素的char*指针

因此,您可以在需要char[]的地方使用您的char*:

#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);
}
#包括
使用名称空间系统;
使用名称空间System::Runtime::InteropServices;
无效显示(字符s[])
{

STD::这不是C++,而是C++语言,CLI是一种不同的语言。@ LealNeasraceSimultReal: ReTaGeGi已经添加了我原来的问题的解决方案,但基本上我发现使用<代码> SpReFTF()是最简单的方法。不需要调用<代码> MARSARAL <代码>函数。谢谢回答,但是这个解决方案对我来说不起作用。我已经尝试了编组,但是这个解决方案不模仿char []。所以我不能用char []来使用这个char。是否有什么想法将C++中的字符串^转换成STD::String??是等效的,因此您可以像使用char[]一样使用char*类型的变量。您是否尝试过将char*传递到您试图调用的例程或方法中?感谢Maurice,您是对的。问题是我使用的是2d静态数组
array[x][sizeof(nativeString]
和value char*不是静态的,正如我将其定义为
char[]=“静态字符串”
我没有注意到这一点,所以当我使用动态数组时,它可以工作。谢谢你的帮助。我很高兴。祝你工作顺利。谢谢你们两位的回答。你是对的,这个转换可以工作。问题是我使用的是静态2d数组
数组[x][sizeof(nativeString]
和value char*不是静态的,当我将其定义为
char[]=“static string”
时,似乎我必须使用动态数组来解决此问题。谢谢