Home >Backend Development >C++ >How to Efficiently Convert Between System::String and std::string in C .NET?
Using the Marshal Class to Convert between System::String and std::string
Translating between System::String in C .NET and std::string in C can be a common task. The marshal_context class provided by MS provides a clean and efficient way to achieve this.
Syntax:
<code class="CPP">msclr::interop::marshal_context context; std::string standardString = context.marshal_as<std::string>(managedString);</code>
Example:
<code class="CPP">#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; }</code>
Benefits:
Alternative Conversions
The MSDN article referenced by the answer also provides other conversion methods, such as:
The above is the detailed content of How to Efficiently Convert Between System::String and std::string in C .NET?. For more information, please follow other related articles on the PHP Chinese website!