C# .NET wrapper library for standard C++ classes

– Enabling you create and access standard C++ class object from C# code


In order for our C# wrapper generator for C++ DLL to automatically generate C# source code for C++ DLL, we would have to have a C# wrapper library for the standard C++ run-time library first. Since we were already writing the C# wrapper generator, we used the C# wrapper generator to create the C# wrapper library for the C++ standard run-time classes after some fine-tuning specifically done to the C# wrapper generator for C++ standard classes.

Here are the list of all the C# wrapper classes in the C# wrapper library and the corresponding standard C++ classes.

C++ is one of most widely used programming languages, and std::string is one of the most widely used C++ standard classes. In a C DLL, we use char *, const char* as a string parameter, and in C# you can use string, String, StringBuilder which are automatically marshaled by .NET framework to map the C style string. But, for std::string used in C DLL or C++ DLL, we do not have that luxury any more. The problem is that .NET does not marshal std::string, you simply can not use .NET string to marshal a c++ std::string which is a C++ class instance, it is not just a pointer to a buffer like char*.

Let’s start discussing StdString, the C# wrapper class for C++ std::string.

The following is the metadata of the StdString C# .NET class. It is exactly what I copied from VS studio IDE.

As you can see, the C# wrapper class, StdString has the exact same interface of the corresponding C++ std::string class in .NET, you can use it just like you use it in C++ language, it also provides a Marshaller class which shall allow it to be used as a custom marshaller.

Let’s look at an example of how we can use StdString.

Assuming we have a C-style method in a DLL named sample.dll.

Without the C# .NET Wrapper library and the StdString C# wrapper class for the C++ string class (std::string), we would not be able to marshal the C++ string (std::string) in C# and can not call the C++ method or C++ class function member neither because we can not simply marshal it as C# string or C# StringBuilder, neither of them will work at all. Now, since we have StdString C# .NET class, the wrapper class of C++ string (std::string), we will be able to marshal the C++ string class (std::string) as StdString as shown by the following code,

One last thing we would want to be clear at the end of this blog article, since the underlying C++ DLL only works with certain version of C++ run-time library, and specifically, Microsoft Visual C++ run-time library, the C# .NET Wrapper library will only with that version of C++ run-time specifically, its the limit of that C++ DLL.

Translate »