How to convert String^ to char array [duplicate]

2020-03-30 01:37发布

问题:

This question already has answers here:
Closed 7 years ago.

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 from TextBox in String^:

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 from TextBox.

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 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.

回答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.



回答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 :)