How to convert String^ to char array [duplicate]

非 Y 不嫁゛ 提交于 2019-12-01 11:37:24
Maurice Reeves

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.

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

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