Converting System Strings Into Standard Strings
Learn about system strings and check out this solution to a common problem when working with C++/CLI: converting System::string^ into std::string.
Join the DZone community and get the full member experience.
Join For FreeC++/CLI (C++ modified for Common Language Infrastructure) is a language specification created by Microsoft and intended to supersede Managed Extensions for C++ that is used in Visual C++. Which means, you can say that C++/CLI is a C++ extension. It is a complete revision that aims to simplify the older Managed C++ syntax, which is now deprecated. So I wanted to use this extension a bit to see what I can do with it.
And I must say that it is awesome to use C++ and also C# features together. It’s like you are writing C++, but when you bored, you can switch into C#.
In this post, I am going to show a solution to the problem of converting System::string^ into std::string. You will face this problem so many times if you decide to use C++/CLI.
What Are System Strings?
System Strings are the types that commonly used in CLR projects. When you made a research on the web, you will see that most of the projects are developed with System::strings^ instead of std::strings.
The difference between System Strings and Standard Strings is about the mapping types into another. In some languages, while you are mapping your variable types into 32 bit, in some languages you can map them into 64 bit. So the fact that using std::string or System::string^ makes no difference is well established.
Is It Still Better to Use String Instead of System.String?
There is no agreed answer on this. It is up to you. For me, I needed to use std::string in my project, so I’ve developed a function to do this. If you needed to use std::string instead of System::string^ like me, you can check out this function:
using System::Runtime::InteropServices::Marshal;
static std::string toStandardString(System::String^ string)
{
System::IntPtr pointer = Marshal::StringToHGlobalAnsi(string);
char* charPointer = reinterpret_cast<char*>(pointer.ToPointer());
std::string returnString(charPointer, string->Length);
Marshal::FreeHGlobal(pointer);
return returnString;
}
Published at DZone with permission of Orcun Yilmaz. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments