Advertisement
fuad_cs22

System String to std::string

Jan 13th, 2021
757
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. // convert_system_string.cpp
  2. // compile with: /clr
  3. #include <string>
  4. #include <iostream>
  5. using namespace std;
  6. using namespace System;
  7.  
  8. void MarshalString ( String ^ s, string& os ) {
  9.    using namespace Runtime::InteropServices;
  10.    const char* chars =
  11.       (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
  12.    os = chars;
  13.    Marshal::FreeHGlobal(IntPtr((void*)chars));
  14. }
  15.  
  16. void MarshalString ( String ^ s, wstring& os ) {
  17.    using namespace Runtime::InteropServices;
  18.    const wchar_t* chars =
  19.       (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
  20.    os = chars;
  21.    Marshal::FreeHGlobal(IntPtr((void*)chars));
  22. }
  23.  
  24. int main() {
  25.    string a = "test";
  26.    wstring b = L"test2";
  27.    String ^ c = gcnew String("abcd");
  28.  
  29.    cout << a << endl;
  30.    MarshalString(c, a);
  31.    c = "efgh";
  32.    MarshalString(c, b);
  33.    cout << a << endl;
  34.    wcout << b << endl;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement