How do you convert System::String to std::string in C++ .NET?
There is no functionality difference between string and std::string because they're the same type.
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.
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.
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
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With