How to convert String^ to char array [duplicate]

泪湿孤枕 提交于 2019-12-01 09:38:33

问题


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



来源:https://stackoverflow.com/questions/13665649/how-to-convert-string-to-char-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!