Aravind's Tutorials

Home
Projects
Research
Publications
Astrophotography
Photography
Tutorials
Reviews
Links
CV

My Images
Blog

Picture of the picosecond
Picture of the picosecond


Wrapping C++ classes with a managed class


In this tutorial I will quickly go over how to wrap a regular C++ class in a managed class for export to .NET. If you don't know how to create managed projects see Creating and using a managed C++ DLL from C# or VB with .NET.

The greatest benefit of the managed C++ project is the ability to easily add a wrapper around your existing C++ library so that it can be used by anything that plugs into the .NET Framework, including C# and VB.NET.

There are a few reasons you may want to wrap your classes rather than directly exposing them:
  • Exposed classes may want to contain fewer functions (.NET exposed classes may be exported to the world in general)
  • Managed classes cannot contain "const" or "volatile" functions
  • Simpler exported class hierarchy (again if the .NET exported classes are meant for "outside of the company" consumption)

One way in which to wrap your class is to keep a pointer to the unmanaged class and reflect all the function calls.
#include "stdafx.h"
#include "stdlib.h"

using namespace System;

class UnManaged
{
private:
	int number;
	double real;

public:
	void DoSomething() const {}
	int GetNumber()
	{
		return number;
	}

	double GetReal()
	{
		return real;
	}

};

namespace ManagedCPPTest {
	__gc public class Managed
	{
	private:
		UnManaged* pBackObj;
	public:
		Managed() : pBackObj( 0 )
		{
			pBackObj = new UnManaged();
		}

		void DoSomething()
		{
			pBackObj->DoSomething();
		}

		double GetReal()
		{
			return pBackObj->GetReal();
		}
	};
};
Notes:
  • We decided not to expose GetNumber, so even though it is available in the unmanaged version, it is hidden in the managed version, effectively hiding that functionality to the rest of the world.
  • In our managed class, "DoSomething" was a const function, thus it cannot be directly exposed.

However, what happens if we have multiple classes that implement the same interface? Would we have to wrap all the implementation classes? This is most relevant when using class factories. See Implementing a class factory in a managed C++ DLL

Return to tutorial index


Hosted by theorem.ca

All text and images (c) 2000-2010 Aravind Krishnaswamy. All rights reserved.