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

Posted on 2007-08-09
Last Modified: 2013-12-14
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;"c:\\test.txt",std::ios::in);
when you run this, it has error to MessageBox simply because it use System::string.

Question by:alwinp
    LVL 19

    Accepted Solution

    You can use a char buffer as a constructor parameter to System::String like so:

        MessageBox::Show(gcnew System::String(str.c_str());

    Author Comment

    Hi drichards;
    It works, how was that happen? I give you the points.
    LVL 19

    Expert Comment

    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.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    The following diagram presents a diamond class hierarchy: As depicted, diamond inheritance denotes when two classes (e.g., CDerived1 and CDerived2), separately extending a common base class (e.g., CBase), are sub classed simultaneously by a fourt…
    Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project ( automates most of the tasks discussed in this article. You can even fin…
    This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
    The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now