MCppWrapper Sample: Demonstrates Wrapping a C++ DLL with Managed Extensions
The MCppWrapper sample illustrates how a Managed Extensions __gc class can be used as a proxy class (or wrapper) for an unmanaged C++ class in a DLL. Some of the basic concepts demonstrated are Managed Extensions interoperability, wrapper and proxy classes, and basic data marshaling.
Building and Running the Sample
To build and run MCppWrapper using Visual Studio
- In the Visual Studio IDE, load the solution file MCppWrapper.sln.
- In Solution Explorer, right-click the Suffix project and click Set as StartUp Project.
- On the Build menu, click Build Solution.
- On the Debug menu, click Start Without Debugging.
How the Sample Works
The unmanaged DLL provides a class called
substring. This has a method called
suffix that returns the suffix of a string from an index position to the end of the string. The first character in the string has index position 1. A position of 0 or a negative position results in the whole string being returned. A position larger than the length of the string results in the empty string being returned.
The substring class is wrapped by a Managed Extensions __gc class called
substring_w. This class contains a method called
find_suffix that takes a managed string and an int as arguments. The method does some simple data marshaling: the managed string is converted to an unmanaged one. It creates an object of the
substring class and calls
suffix with the converted string and integer position. The string returned is converted implicitly to a managed String.
The client of the
substring_w class is a simple Visual C# program that reads a string and position from the console, and then creates a
substring_w object, calls
find_suffix, and displays the suffix.
This sample demonstrates the following keywords:
__gc; __declspec(dllexport); __declspec(dllimport); Int32.Parse; LocalFree; LocalAlloc