I try to convert a String^ to basic string...but I get the error after this code. What does it mean and how can I fix it? I need to input basic string into a class constructor. The string^ would not work.
System::String^ temp = textBox1->Text;
string dummy = System::Convert::ToString(temp);
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
You need to marshal your string. The managed string sits somewhere on the managed heap (garbage collector is free to move it around).
One way of getting the string to the native side is as follows:
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
If you are using Visual Studio 2008, you can take advantage of much nicer marshaling utilities. Check out this MSDN page.
#include <msclr/marshal.h>
#include <msclr/marshal_cppstd.h>
using namespace msclr::interop;
std::string nativeString(marshal_as<std::string>(managedString));
I spend 11h to find a solution:
#include <stdlib.h
#include <string.h>
#include <msclr\marshal_cppstd.h>
//ListaQuad<int> prueba;
//..
using namespace msclr::interop;
//..
System::String^ clrString = (TextoDeBoton);
std::string stdString = marshal_as<std::string>(clrString); //String^ to std
//System::String^ myString = marshal_as<System::String^>(MyBasicStirng); //std to String^ (no lo he probado, pero sería algo así.)
prueba.CopyInfo(stdString); //MyMethod
//..
//where, String^ = TextoDeBoton;
//and, stdString = normal string;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With