将String ^转换为std :: string(基本字符串) - >错误.我怎样才能解决这个问题?

2 c++ string std

我尝试将String ^转换为基本字符串...但是我在此代码后得到错误.它是什么意思,我该如何解决?我需要将基本字符串输入到类构造函数中.字符串^不起作用.

System::String^ temp = textBox1->Text;
string dummy = System::Convert::ToString(temp);
Run Code Online (Sandbox Code Playgroud)
error C2440: 'initializing' : cannot convert from 'System::String ^' to 'std::basic_string'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits,
1>            _Ax=std::allocator
1>        ]
1>        No constructor could take the source type, or constructor overload resolution was ambiguous

Fil*_*ącz 8

你需要编组你的字符串.托管字符串位于托管堆上的某个位置(垃圾收集器可以自由移动它).

将字符串转换为本机的一种方法如下:

using System::Runtime::InteropServices::Marshal;

char *pString = (char*)Marshal::StringToHGlobalAnsi(managedString);
std::string nativeString(pString); // make your std::string
Marshal::FreeHGlobal(pString);     // don't forget to clean up
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Visual Studio 2008,则可以利用更好的编组实用程序.查看此MSDN页面.

#include <msclr/marshal.h>
#include <msclr/marshal_cppstd.h>

using namespace msclr::interop;

std::string nativeString(marshal_as<std::string>(managedString));
Run Code Online (Sandbox Code Playgroud)