Rapidly Developing C++ Libraries for Unity

Ian Thomas
2 min readJun 15, 2023

--

I’ve recently been developing an external library in C++ for a hobby project, and I ran into an annoying (and known!) problem.

The Problem

When Unity starts, it loads the external library, and calls into it when it needs to run a function inside the library. Which is fine!

Unfortunately if you’re developing the library, you often need to recompile the library file and replace the one that was there. Unfortunately Unity doesn’t automatically reload the external library – since it’s already loaded the old version, and it uses that copy! So it’s very hard to test incremental changes.

A Solution

This is a problem a few people have come up solutions for. I’ve been using Forrest Smith’s NativePluginLoader.cs script, which solves the issue by providing a slightly different pattern to the standard. It works nicely!

What’s Different?

The change is to move from a standard PInvoke method:

public static class MyPlugin 
{
[DllImport("myplugin", EntryPoint = "somePluginMethod")]
extern static public bool SomePluginMethod(int someParam);
}

To this method, which assumes Forrest’s class is available:

[PluginAttr("myplugin")]
public static class MyPlugin
{
[PluginFunctionAttr("somePluginMethod")]
public static _somePluginMethod SomePluginMethod;
public delegate bool _sumPluginMethod(int someParam);
}

void DoSomething() {
bool didItWork = MyPlugin.SomePluginMethod(517);
}

Forrest’s script uses magic via the PluginAttr and PluginFunctionAttr to load and reload the external library (which will be a .dll on Windows or a .dylib on Mac) as needed.

Incremental develop is possible! Thanks Forrest!

On Mac too!

Unfortunately when I first came across it it was only available for Windows. I was working on a Mac, so I’ve updated it to work on Mac as well. Forrest has added my code to his GitHub repository – you can find the updated solution here.

--

--

Ian Thomas

Ian is narrative director, coder, and writer of video games, films, larp, books, and VR/AR experiences. He has worked on well over 100 titles.