Converting System Strings into Standard Strings
C++/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 a problem, which is converting System::string^ into std::string. You will face up with this problem so many times if you decide to use C++/CLI.
What is System String
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 better to still use string instead of System.String?
There is no agreed answer on this. It is up to you. Per me, I was 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 the function:
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);