How to make C++ DLL and use it in Unity

Overview

Define a C++ class

#pragma once#ifdef DLLPROJECT_EXPORTS
# define EXPORT __declspec(dllexport)
#else
# define EXPORT __declspec(dllimport)
#endif
class Hoge
{
public:
int Foo(int a);
};
extern "C" EXPORT Hoge* createHoge();
extern "C" EXPORT void freeHoge(Hoge* instance);
extern "C" EXPORT int getResult(Hoge* instance, int a);

What are __declspec(dllexport) and __declspec(dllimport) ?

What is extern “C”?

Implement the C++ class

#include "pch.h"
#include "Hoge.h"
int Hoge::Foo(int a)
{
return a + 5;
}
EXPORT Hoge* createHoge() {
return new Hoge();
}
EXPORT void freeHoge(Hoge* instance) {
delete instance;
}
EXPORT int getResult(Hoge* instance, int a) {
return instance->Foo(a);
}

Build the class with VisualStudio

Let’s use the class in Unity

using System;
using System.Runtime.InteropServices;
using UnityEngine;
public class DLLTest : MonoBehaviour
{
[DllImport("DLL-Sample.dll")]
private static extern IntPtr createHoge();

[DllImport("DLL-Sample.dll")]
private static extern void freeHoge(IntPtr instance);

[DllImport("DLL-Sample.dll")]
private static extern int getResult(IntPtr instance, int a);

private void Start()
{
IntPtr hoge = createHoge();
Debug.Log(hoge); // => Show the pointer address.
int result = getResult(hoge, 10);
Debug.Log(result); // => 15
freeHoge(hoge);
}
}

How to use a struct between C++ and C#?

typedef struct _Person
{
int id;
int age;
} Person;
EXPORT void createPerson(Hoge* instance, Person* person)
{
(*person).age = 15;
}
[DllImport("DLL-Sample.dll")]
private static extern void createPerson(IntPtr instance, ref Person person);
private void Start()
{
IntPtr instance = createHoge();
Person person = new Person();
createPerson(instance, ref person);
Debug.Log(person.age); // => 15
}

Conclusion

--

--

I’m an AR engineer. I work at MESON.inc

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store