Using C++ classes in native DLL for Unity

I’d like to use classes written in my C++ native plugin in Unity. Here’s my attempt.

The C++ code (compiles fine):

// frontengine.cpp

#include "stdafx.h"
#include "FrontENGINE.h"

extern "C++" {
	FRONTENGINE_API int Add(int a, int b) {
		return a + b + 10;

	FRONTENGINE_API class TestClass {
		int var;
		void setvar(int a) {
			var = a;

		int getvar() {
			return var;

The Unity Code:

 // dosomething.cs
using System.Runtime.InteropServices;

public class DoStuff : MonoBehaviour {
	static extern int Add(int a, int b);

	void Start() {

		TestClass nq = new TestClass();

What I get when I try this:

error CS0246: The type or namespace name `TestClass' could not be found. Are you missing an assembly reference?

You can’t directly use C++ classes in C#. The memory management works completely different. In Unity you can only use static “std call” methods that are exported in an extern "C" section. extern “C” is required since C++ uses name mangling to encode the signature of the method into it’s name. This mangling is not really standardised and depends on the C++ compiler you’re using.

If you really need to use a C++ class in C# you have to create a wrapper with static methods like i explained over here. So any instance method you want to call from C# need to have a static wrapper method.