Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 389
  • Last Modified:

How to convert std::string to System::String

Hi EE,
I'm new to C++ and I have a problem figuring out this code, it won't work:
I'm using Microsoft Visual C++ Express 2005
====================================
string str;      
ifstream myfile;
myfile.open("c:\\test.txt",std::ios::in);
getline(myfile,str);
MessageBox::Show(str);
myfile.close();
====================================
when you run this, it has error to MessageBox simply because it use System::string.

thanks
0
alwinp
Asked:
alwinp
  • 2
1 Solution
 
drichardsCommented:
You can use a char buffer as a constructor parameter to System::String like so:

    MessageBox::Show(gcnew System::String(str.c_str());
0
 
alwinpAuthor Commented:
Hi drichards;
It works, how was that happen? I give you the points.
Thanks.
0
 
drichardsCommented:
std::string is a standard C++ type created on the unmanaged heap and System::String is a CLR (.NET) type created on the managed heap.  You cannot use a managed object in native C++ code or an unmanaged object in managed C++ code without special considerations (usually involves marshaling data from one space to the other or pinning pointers).  That's why your original attempt to pass the std::string as a parameter to the .NET MessageBox::Show method failed.  The System::String constructor can take a standard C++ char array (or wide char array) and it copies the string to managed memory.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now