将String ^转换为标准C ++字符串

时间:2011-12-20 21:17:17

标签: string visual-c++

我遇到了问题cannot convert parameter from 'System::String ^' to 'std::string'。如何在Visual C ++环境中将System :: String ^转换为标准C ++字符串?

2 个答案:

答案 0 :(得分:2)

来自this link at Microsoft

void MarshalString ( String ^ s, string& os ) {
    using namespace Runtime::InteropServices;
    const char* chars = 
       (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
    os = chars;
    Marshal::FreeHGlobal(IntPtr((void*)chars));
}

int main() {
    string a = "test";
    String ^ c = gcnew String("abcd");
    cout << a << endl;
    MarshalString(c, a);
    cout << a << endl;
}

答案 1 :(得分:0)

 //*** convert String^ to standard C++ string

 ` String ^SyStr = "abc"; // system string
   string StStr ="";      // standard string
   for each (char c in SyStr )
   {
       StStr .push_back( c);
   } `

   //**** End convert String^ to standard C++ string 

   //****  convert standard C++ string to  String^ 

  ` String ^SyStr = "";  // system string
    string StStr ="xyz"; // standard string
    SyStr = gcnew String(StStr.c_str());`

    //**** End  convert standard C++ string to  String^