Skip to main content
Be Bitwise
C++C++ Systems Programming

Plugin Architecture

A plugin system lets your application grow new behaviour without a rebuild. Drop a shared library into a directory, the host scans, loads, calls in. Same pattern behind VST audio effects, Apache modules, Photoshop filters, and every game engine that lets modders ship code.

The Plugin Interface

It hinges on one thing: a stable interface both sides agree on.

cpp
// plugin_interface.h - shared between host and plugins
#pragma once
#include <string>
class IPlugin {
public:
virtual ~IPlugin() = default;
virtual std::string name() const = 0;
virtual std::string version() const = 0;
virtual bool initialize() = 0;
virtual void process(const std::string& input, std::string& output) = 0;
virtual void shutdown() = 0;
};
// C-linkage factory function type
// Using extern "C" avoids name mangling issues
extern "C" {
using CreatePluginFn = IPlugin* (*)();
using DestroyPluginFn = void (*)(IPlugin*);
}
#define DECLARE_PLUGIN(ClassName) \
extern "C" IPlugin* create_plugin() { return new ClassName(); } \
extern "C" void destroy_plugin(IPlugin* p) { delete p; }
Key Concept

extern "C" switches off C++ name mangling for those entry points. With mangling on, the symbol becomes something like _Z13create_pluginv and dlsym("create_plugin") returns null. So plugin interfaces always expose C-linkage entry points, even when the plugin's implementation is wall-to-wall C++.

extern "C" only fixes the names, though. This interface still passes std::string by value and reference and leans on the compiler's vtable layout, so host and plugin must be built with the same compiler family and the same standard library (and, with libstdc++, the same _GLIBCXX_USE_CXX11_ABI setting). A libc++ plugin handed a libstdc++ std::string will read garbage. That's fine for plugins you build alongside the host. For third-party plugins, keep the boundary to plain C types (const char* plus a length, fixed-width integers, POD structs) or pure-virtual interfaces whose methods only take those.

A Sample Plugin

cpp
// uppercase_plugin.cpp
#include "plugin_interface.h"
#include <algorithm>
#include <cctype>
class UppercasePlugin : public IPlugin {
public:
std::string name() const override { return "uppercase"; }
std::string version() const override { return "1.0.0"; }
bool initialize() override {
return true;
}
void process(const std::string& input, std::string& output) override {
output = input;
std::transform(output.begin(), output.end(), output.begin(),
[](unsigned char c) { return std::toupper(c); });
}
void shutdown() override {}
};
DECLARE_PLUGIN(UppercasePlugin)

Compile as a shared library:

bash
g++ -shared -fPIC -o uppercase_plugin.so uppercase_plugin.cpp

The Plugin Loader

cpp
#include <algorithm>
#include <dlfcn.h>
#include <filesystem>
#include <memory>
#include <vector>
#include <iostream>
#include "plugin_interface.h"
namespace fs = std::filesystem;
struct LoadedPlugin {
void* handle;
IPlugin* plugin;
DestroyPluginFn destroy;
fs::path path;
LoadedPlugin(void* h, IPlugin* p, DestroyPluginFn d, fs::path where)
: handle(h), plugin(p), destroy(d), path(std::move(where)) {}
~LoadedPlugin() {
if (plugin && destroy) {
plugin->shutdown();
destroy(plugin);
}
if (handle) dlclose(handle);
}
// Non-copyable
LoadedPlugin(const LoadedPlugin&) = delete;
LoadedPlugin& operator=(const LoadedPlugin&) = delete;
LoadedPlugin(LoadedPlugin&& other) noexcept
: handle(other.handle), plugin(other.plugin), destroy(other.destroy),
path(std::move(other.path)) {
other.handle = nullptr;
other.plugin = nullptr;
other.destroy = nullptr;
}
};
class PluginManager {
std::vector<std::unique_ptr<LoadedPlugin>> plugins_;
public:
bool load_plugin(const fs::path& path) {
void* handle = dlopen(path.c_str(), RTLD_LAZY);
if (!handle) {
std::cerr << "dlopen: " << dlerror() << "\n";
return false;
}
auto create = (CreatePluginFn)dlsym(handle, "create_plugin");
auto destroy = (DestroyPluginFn)dlsym(handle, "destroy_plugin");
if (!create || !destroy) {
std::cerr << "Missing factory functions in " << path << "\n";
dlclose(handle);
return false;
}
auto loaded = std::make_unique<LoadedPlugin>(handle, create(), destroy, path);
if (!loaded->plugin->initialize()) {
std::cerr << "Plugin initialisation failed: " << path << "\n";
return false;
}
std::cout << "Loaded: " << loaded->plugin->name()
<< " v" << loaded->plugin->version() << "\n";
plugins_.push_back(std::move(loaded));
return true;
}
void load_directory(const fs::path& dir) {
for (const auto& entry : fs::directory_iterator(dir)) {
if (entry.path().extension() == ".so" ||
entry.path().extension() == ".dylib") {
load_plugin(entry.path());
}
}
}
void process_all(const std::string& input) {
for (auto& loaded : plugins_) {
std::string output;
loaded->plugin->process(input, output);
std::cout << loaded->plugin->name() << ": " << output << "\n";
}
}
};

shared_ptr Across DLL Boundaries

Passing std::shared_ptr across a shared library boundary is one of those things that looks fine until it crashes in the field:

cpp
// DANGEROUS: different allocators may be used
// The plugin creates with new, the host deletes
// If they link different C++ runtimes, this crashes
// SAFE: the plugin provides both create and destroy
// The shared_ptr uses the plugin's deleter
std::shared_ptr<IPlugin> safe_load(void* handle) {
auto create = (CreatePluginFn)dlsym(handle, "create_plugin");
auto destroy = (DestroyPluginFn)dlsym(handle, "destroy_plugin");
IPlugin* raw = create();
return std::shared_ptr<IPlugin>(raw, [destroy](IPlugin* p) {
destroy(p);
});
}

The rule of thumb is that memory goes back to whoever handed it out. Trace the safe version across the boundary:

The vtable box is the other half of the danger. Every virtual call on that pointer jumps into code inside the plugin, so dlclose must wait until the last shared_ptr is gone, otherwise the next call lands in unmapped memory.

Versioning

Your interface will drift over time. Plan for the day someone tries to load a plugin built against the old one:

cpp
// Add a version query to the C interface
extern "C" {
using GetAPIVersionFn = int (*)();
}
#define CURRENT_API_VERSION 2
// In the loader:
auto get_version = (GetAPIVersionFn)dlsym(handle, "get_api_version");
if (!get_version || get_version() != CURRENT_API_VERSION) {
std::cerr << "Incompatible plugin version\n";
dlclose(handle);
return false;
}

Hot Reloading

During development, reloading a plugin without restarting the host is the difference between a fluid edit cycle and a frustrating one:

cpp
void reload_plugin(const fs::path& path) {
// Find and unload the existing plugin
auto it = std::find_if(plugins_.begin(), plugins_.end(),
[&path](const auto& p) { return p->path == path; });
if (it != plugins_.end()) {
plugins_.erase(it); // Destructor handles cleanup
}
// Load the new version
load_plugin(path);
}

Game engines do this for live-coding workflows. A file watcher spots the rebuild, the engine swaps the plugin out underneath the running game, your gameplay tweak shows up without a restart.

Common Pitfalls

  1. Whether a plugin's static variables survive a reload depends on whether dlclose really unmapped it. If the reference count hit zero and nothing else needs its symbols, a fresh dlopen starts them from scratch. But RTLD_NODELETE, a second handle you forgot about, or (with GCC on glibc) STB_GNU_UNIQUE symbols from template statics and inline-function statics all keep the old copy alive, and then the "new" version silently isn't loaded. GCC's -fno-gnu-unique turns that last one off.
  2. RTTI across the boundary is unreliable. Two typeids for the same class can compare unequal if they came from different libraries.
  3. Throwing an exception from plugin into host is undefined territory across compiler vendors. Catch at the boundary.
  4. Pin symbol visibility down. Export the entry points and nothing else (-fvisibility=hidden plus selective __attribute__((visibility("default")))).
  5. dlopen and dlclose are themselves thread-safe, but nothing stops one thread unloading a plugin while another is still running its code. Make sure no thread is inside the plugin, or holding a pointer into it, before you dlclose.