- Home /
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;
public:
void setvar(int a) {
var = a;
}
int getvar() {
return var;
}
};
}
The Unity Code:
// dosomething.cs
using System.Runtime.InteropServices;
public class DoStuff : MonoBehaviour {
[DllImport("FRONT-Engine")]
static extern int Add(int a, int b);
void Start() {
Debug.Log("Test");
TestClass nq = new TestClass();
nq.setvar(43);
Debug.Log(nq.getvar());
}
}
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?
Answer by Bunny83 · Jun 14, 2017 at 01:06 AM
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.
Your answer
Follow this Question
Related Questions
How to step into a native C++ dll in Visual Studio? 0 Answers
Releasing plugin in script 0 Answers
Custom swift framework in Unity iOS game 0 Answers
CFStringGetCharacters in Unity5.0 crash? 2 Answers