Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI Converting from System::String^ to std::string

Can someone please post a simple code that would convert,

System::String^ 

To,

C++ std::string

I.e., I just want to assign the value of,

String^ originalString; 

To,

std::string newString; 
like image 487
sivabudh Avatar asked Jun 03 '09 19:06

sivabudh


People also ask

What is the difference between string and std::string?

Differences between std::string and String Pavan. std::string is the string class from the standard C++ library. String is some other string class from some other library. It's hard to say from which library, because there are many different libraries that have their own class called String.

What does std::string () do?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

What is std::string in C?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.


2 Answers

Don't roll your own, use these handy (and extensible) wrappers provided by Microsoft.

For example:

#include <msclr\marshal_cppstd.h>  System::String^ managed = "test"; std::string unmanaged = msclr::interop::marshal_as<std::string>(managed); 
like image 66
tragomaskhalos Avatar answered Sep 22 '22 05:09

tragomaskhalos


You can easily do this as follows

#include <msclr/marshal_cppstd.h>  System::String^ xyz="Hi boys";   std::string converted_xyz=msclr::interop::marshal_as< std::string >( xyz); 
like image 23
Sriwantha Attanayake Avatar answered Sep 20 '22 05:09

Sriwantha Attanayake