C++/CLI Wrapper - marshalling strings

As mentioned previously, C++/CLI code makes use of managed data types to pass data between C# and C++. Primitive data types are not affected by this (int, double, bool, etc.) but others, such as strings, are.

Marshalling strings between system and std

Strings in C# are referred to as System Strings as they are a part of the System namespace (inheriting from System.Object). Strings in C++ are referred to as std strings as they come from the std namespace. However, despite both being containers for strings of text, there is no direct conversion or casting available between them. I.e. you cannot simply do:
std::string = (std::string)SomeSystemString;

Instead you need to 'marshal' your strings between the System and the Std namespaces. This is done using the marshal_as function from the msclr namespace.

Includes

To use the marshalling service, you need to include the marshal_cppstd.h header file into either your header file or cpp file. This header is a part of the msclr folder and the full include path is:
#include <msclr\marshal_cppstd.h>

Marshalling strings

Marshalling strings between system and std namespaces

Marshalling strings between system and std namespaces


Once you have included the marshal_cppstd.h header file, you can begin marshalling strings between the system string format and the std string format. Below are two examples showing how to marshal a system string to become a std string and vice versa.

std::string myStdString = msclr::interop::marshal_as<std::string>(someSystemString);
String^ mySystemString = msclr::interop::marshal_as<String^>(someStdString);

As you can see, the method call is identical until you some to fill in the chevron brackets for which string you wish the output to be. Notice the use of '^' as this is managed code for the C++/CLI wrapper, and you need to use the '^' to denote this.

Leave a Reply

Your email address will not be published. Required fields are marked *