What is the best way to convert between char* and System::String in C++/CLI

前端 未结 5 618
情深已故
情深已故 2020-11-29 01:07

What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appea

5条回答
  •  再見小時候
    2020-11-29 01:39

    System::String has a constructor that takes a char*:

     using namespace system;
     const char* charstr = "Hello, world!";
     String^ clistr = gcnew String(charstr);
     Console::WriteLine(clistr);
    

    Getting a char* back is a bit harder, but not too bad:

     IntPtr p = Marshal::StringToHGlobalAnsi(clistr);
     char *pNewCharStr = static_cast(p.ToPointer());
     cout << pNewCharStr << endl;
     Marshal::FreeHGlobal(p);
    

提交回复
热议问题