Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String^ to std::string (basic string) -> Error. How can I fix this?

Tags:

c++

string

std

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

2 Answers

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));
like image 158
Filip Frącz Avatar answered May 27 '26 13:05

Filip Frącz


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;
like image 26
Alejandro Perea Avatar answered May 27 '26 13:05

Alejandro Perea