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


Define a C++ class

#pragma once#ifdef DLLPROJECT_EXPORTS
# define EXPORT __declspec(dllexport)
# define EXPORT __declspec(dllimport)
class Hoge
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
private static extern IntPtr createHoge();

private static extern void freeHoge(IntPtr instance);

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

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;
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




I’m an AR engineer. I work at

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