Home >Backend Development >C++ >How do I convert a System::String to a std::string in C .NET?
Converting System::String to std::string in C .NET
In C .NET, converting a System::String to a std::string can be achieved using the marshaling feature provided by the Microsoft .NET Framework.
To convert a System::String to a std::string, you can use the marshal_as method provided by the msclr::interop::marshal_context class. This method takes the managed string as input and returns the corresponding standard string.
Here's an example of how to convert a System::String to a std::string:
<code class="cpp">#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; }</code>
This code snippet imports the necessary headers, declares a managed string, and then uses the marshal_as method to convert the managed string to a standard string.
It's important to note that the msclr::interop namespace is only available in recent versions of .NET. If you're using an older version, you can use the msclr::interop::marshal_as_string method instead.
For more information on converting various other types between managed and unmanaged code, refer to the following MSDN article: https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/interop/marshaling-data-with-platform-invoke
The above is the detailed content of How do I convert a System::String to a std::string in C .NET?. For more information, please follow other related articles on the PHP Chinese website!