Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ .NET convert System::String to std::string

How do you convert System::String to std::string in C++ .NET?

like image 304
Amish Programmer Avatar asked Aug 19 '09 15:08

Amish Programmer


People also ask

Is std::string the same as string?

There is no functionality difference between string and std::string because they're the same type.

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

There is cleaner syntax if you're using a recent version of .net

#include "stdafx.h" #include <string>  #include <msclr\marshal_cppstd.h>  using namespace System;  int main(array<System::String ^> ^args) {     System::String^ managedString = "test";      msclr::interop::marshal_context context;     std::string standardString = context.marshal_as<std::string>(managedString);      return 0; } 

This also gives you better clean-up in the face of exceptions.

There is an msdn article for various other conversions

like image 128
Colin Gravill Avatar answered Oct 11 '22 09:10

Colin Gravill


And in response to the "easier way" in later versions of C++/CLI, you can do it without the marshal_context. I know this works in Visual Studio 2010; not sure about prior to that.


#include "stdafx.h" #include <string>  #include <msclr\marshal_cppstd.h>  using namespace msclr::interop;  int main(array<System::String ^> ^args) {     System::String^ managedString = "test";      std::string standardString = marshal_as<std::string>(managedString);      return 0; } 

like image 36
Mike Johnson Avatar answered Oct 11 '22 09:10

Mike Johnson