Photo by Susan Q Yin on Unsplash
Dynamic plugins let you add new features to an application without rebuilding it. You compile a plugin into a shared library, put it next to your app, and the app loads it when needed.
This is how text editors load syntax highlighting, game engines load mods, and servers load additional handlers.
I’ve done that in the past with C++ but I was wondering how to do this in Rust, so decided to check it. Turns out, Rust supports this, but there’s one important thing to know: Rust does not have a stable ABI.
The solution is to use a C ABI as the boundary between the app and its plugins.
In practice, this means exposing simple C-compatible functions and structs. We can then build a more convenient Rust API on top of them, using traits and normal Rust types.
In this post, we’ll build a plugin system in two steps.
First, we’ll create a very simple version with just one function. Then we’ll improve it by splitting the code into three crates: an API, a plugin, and a host application.
The complete code is available in the rust-plugin-example repository. The main and plugin-module branches contain the two versions.
The simplest possible version
Let’s start with a single Cargo package containing two files:
plugin.rscontains our plugin and is compiled as acdylib.host.rscontains the application that loads the plugin.
[package]
name = "plugin-tut"
version = "0.1.0"
edition = "2024"
[lib]
name = "example_plugin"
path = "plugin.rs"
crate-type = ["cdylib"]
[[bin]]
name = "host"
path = "host.rs"
[dependencies]
libloading = "0.9"
The plugin only needs to expose one function:
// plugin.rs
use std::ffi::c_char;
#[unsafe(no_mangle)]
pub extern "C" fn plugin_view() -> *const c_char {
c"Hello from plugin!".as_ptr()
}
There are three important things happening here:
extern "C"tells Rust to use the C calling convention instead of its own.#[unsafe(no_mangle)]keeps the function name unchanged, so the host can find it in the library.c"..."creates a C string that ends with a NUL byte. We return a pointer to it.
Now let’s load this function from the host application using libloading:
use libloading::Library;
use std::ffi::{CStr, c_char};
fn load(path: &str) -> Option<String> {
unsafe {
let lib = Library::new(path).ok()?;
let view = lib
.get::<unsafe extern "C" fn() -> *const c_char>(b"plugin_view\0")
.ok()?;
let ptr = view();
if ptr.is_null() {
return None;
}
Some(CStr::from_ptr(ptr).to_string_lossy().into_owned())
}
}
Library::get finds the function by name and converts it into a function pointer with the signature we expect.
We then call it, check that the returned pointer isn’t null, and convert the C string into a Rust String.
Notice that we copy the string before the library goes out of scope. This is important because unloading the library could invalidate the memory used by the returned pointer.
Build the plugin first, then run the host:
$ cargo build
$ cargo run --bin host -- target/debug/libexample_plugin.dylib
Text loaded from plugin: Hello from plugin!
That’s it! We have a working dynamic plugin system.
It’s a good starting point, but there are a few problems:
- No state. The plugin is just a function. It can’t store configuration or remember anything between calls.
- No versioning. The host and plugin must use exactly the same function signature. If one changes and the other doesn’t, things can go wrong.
- Duplicated declarations. The function signature is written in both the host and the plugin. We have to remember to keep them in sync.
- Limited strings. C strings end at the first NUL byte. They also require us to scan the memory to find where the string ends.
Let’s fix these problems by introducing a shared API crate.
The three-crate workspace
The next version uses a Cargo workspace with three crates:
Cargo.toml workspace configuration
plugin_api/ shared Plugin trait and C-compatible ABI
example_plugin/ example implementation, built as a cdylib
host/ libloading-based host
Both the host and the plugin depend on plugin_api crate. It contains the shared interface, so we only need to define it once.
Neither the host nor the plugin needs to depend directly on the other. That’s how I’ve done it in the past but to be honest, I needed to get some help and search how to do something like this in Rust.
Here’s what I’ve found.
The API crate: a trait behind a function table
Let’s start with a simple Rust trait:
pub trait Plugin {
fn view(&self) -> &str;
}
This is the interface that plugin developers will implement.
However, we can’t pass this trait directly between libraries because Rust doesn’t have a stable ABI.
Instead, we’ll use a C-compatible struct called a function table:
#[derive(Clone, Copy)]
#[repr(C)]
pub struct PluginDescriptor {
pub api_version: u32,
pub create: unsafe extern "C" fn() -> *mut c_void,
pub destroy: unsafe extern "C" fn(instance: *mut c_void),
pub view: unsafe extern "C" fn(instance: *const c_void) -> PluginStr,
}
Instead of passing a Rust object to the host, the plugin gives it this struct containing function pointers.
The host can use these functions to create a plugin instance, call it, and destroy it.
The plugin also uses an opaque pointer (*mut c_void) to represent its instance. The host can store and pass this pointer around, but it doesn’t need to know what type of object it points to. If you’ve written some C code in the past, this is typical coding pattern (passing void* pointers).
We can generate the function table from a normal Rust trait implementation:
impl PluginDescriptor {
pub const fn new<P>() -> Self
where
P: Plugin + Default + 'static,
{
unsafe extern "C" fn create<P>() -> *mut c_void
where
P: Plugin + Default + 'static,
{
Box::into_raw(Box::new(P::default())).cast()
}
unsafe extern "C" fn view<P>(instance: *const c_void) -> PluginStr
where
P: Plugin + Default + 'static,
{
let plugin = unsafe { &*instance.cast::<P>() };
PluginStr::from_str(plugin.view())
}
// destroy::<P> drops the instance; omitted for brevity
Self {
api_version: PLUGIN_API_VERSION,
create: create::<P>,
destroy: destroy::<P>,
view: view::<P>,
}
}
}
The important part is that the host never needs to know the actual plugin type.
Here’s what happens:
createcreates a new plugin instance and returns a pointer to it.viewconverts that pointer back to the original plugin type and calls itsviewmethod.destroytakes care of cleaning up the plugin instance.
The plugin’s real Rust type stays on the plugin side. We only pass a simple pointer and function pointers across the library boundary.
Let’s take a look at the code:
pub const fn new<P>() -> Self
where
P: Plugin + Default + 'static,
This constructor monomorphizes (Rust takes generic code and generates concrete code for each type you use. - i32, String, etc.) three internal C-compatible “trampoline” functions for the concrete type P:
- create:
Box::into_raw(Box::new(P::default())).cast()
Allocates the plugin on the heap and relinquishes ownership, returning an opaque *mut c_void.
- destroy:
drop(Box::from_raw(instance.cast::<P>()));
Reconstructs the Box<P> from the raw pointer and drops it.
IMPORTANT
Allocator symmetry: Because destroy runs inside the plugin library, the memory is allocated and deallocated by the same allocator instance, avoiding crashes when the host and plugin dynamic libraries use different allocators.
- view:
let plugin = unsafe { &*instance.cast::<P>() };
PluginStr::from_str(plugin.view())
Casts the opaque pointer back to &P, invokes the trait method, and converts the resulting &str into a PluginStr.
is_compatible(&self):
Validates whether self.api_version == PLUGIN_API_VERSION
Versioning
Now that we have a shared interface, we also need a way to check whether the host and plugin are compatible.
We can add a version number to PluginDescriptor:
pub const PLUGIN_API_VERSION: u32 = 1;
impl PluginDescriptor {
pub const fn is_compatible(&self) -> bool {
self.api_version == PLUGIN_API_VERSION
}
}
Whenever we change the structure or behaviour of the API, we should update this version.
The host can check the version before using the plugin. If they don’t match, it can return an error instead of trying to use an incompatible interface.
Strings with a pointer and a length
In the first version, we returned a C string using *const c_char.
We can improve this by returning a pointer and its length:
#[derive(Clone, Copy)]
#[repr(C)]
pub struct PluginStr {
ptr: *const u8,
len: usize,
}
This is a simple way to pass strings between the host and the plugin.
The host uses from_raw_parts to create a byte slice from the pointer and length.
There are a couple of benefits:
- We don’t need to scan the memory to find the end of the string.
- Strings can contain NUL bytes.
- Empty strings are easy to handle.
The string memory still belongs to the plugin. The host simply copies it into its own String while the plugin instance is alive.
This keeps memory ownership simple and avoids problems with different memory allocators.
The export macro
We also want plugin developers to avoid writing the same C ABI code every time.
We can do that with a macro:
#[macro_export]
macro_rules! export_plugin {
($plugin:ty) => {
#[unsafe(no_mangle)]
pub extern "C" fn plugin_entry() -> $crate::PluginDescriptor {
$crate::PluginDescriptor::new::<$plugin>()
}
};
}
This macro creates the entry point that the host will look for when loading a plugin.
Plugin developers only need to tell it which type implements the Plugin trait.
The plugin: just implement the trait
With the API crate ready, writing a plugin becomes very simple.
We just create a type and implement the Plugin trait:
use plugin_api::Plugin;
#[derive(Default)]
struct ExamplePlugin;
impl Plugin for ExamplePlugin {
fn view(&self) -> &str {
"Hello from plugin!"
}
}
plugin_api::export_plugin!(ExamplePlugin);
That’s all the plugin code we need.
The plugin’s Cargo.toml declares it as a cdylib and adds a dependency on plugin-api:
[lib]
crate-type = ["cdylib"]
[dependencies]
plugin-api = { path = "../plugin_api" }
Notice that the plugin doesn’t depend on the host. Both use the same API crate.
We can also store data inside the plugin struct. For example, a plugin could load configuration when it’s created and return different text depending on its internal state.
The host: loading the plugin
The host is responsible for loading the library and managing the plugin instance.
This is also where we need to be careful about memory safety.
We can keep everything related to a loaded plugin in one struct:
struct LoadedPlugin {
instance: NonNull<c_void>,
descriptor: PluginDescriptor,
_library: Library, // declared last, so it drops after `instance`
}
There is an important detail here: the library must stay loaded as long as we use the plugin instance.
The plugin’s functions live inside that library. If we unload it too early, calling one of those functions would be unsafe.
That’s why we store the Library inside LoadedPlugin.
Rust drops struct fields in declaration order. By putting _library last, we make sure the plugin instance is destroyed before the library is unloaded.
Now let’s look at the loading process:
unsafe fn load(path: &Path) -> Result<Self, LoadError> {
let library = unsafe { Library::new(path) }.map_err(LoadError::Open)?;
let entry = unsafe { library.get::<PluginEntryPoint>(PLUGIN_ENTRY_POINT) }
.map_err(LoadError::EntryPoint)?;
let descriptor = unsafe { entry() };
if !descriptor.is_compatible() {
return Err(LoadError::VersionMismatch {
expected: PLUGIN_API_VERSION,
found: descriptor.api_version,
});
}
let instance = NonNull::new(unsafe { (descriptor.create)() })
.ok_or(LoadError::CreateInstance)?;
Ok(Self { instance, descriptor, _library: library })
}
The host goes through a few steps:
- Opens the shared library.
- Finds the plugin entry point.
- Gets the plugin descriptor.
- Checks whether the API versions match.
- Creates a plugin instance.
Each step can fail, and we return a different error for each problem.
For example, we can tell the difference between a missing library, a missing entry point, an incompatible API version, and a failed instance creation.
This is much better than returning None for every error, as we did in the first version.
Calling the plugin is also straightforward:
fn view(&self) -> String {
let text = unsafe { (self.descriptor.view)(self.instance.as_ptr()) };
let bytes = unsafe { text.as_bytes() };
String::from_utf8_lossy(bytes).into_owned()
}
impl Drop for LoadedPlugin {
fn drop(&mut self) {
unsafe { (self.descriptor.destroy)(self.instance.as_ptr()) };
}
}
When we call view, the host gets a pointer and length from the plugin and copies the data into its own String.
When LoadedPlugin is dropped, it calls destroy to clean up the plugin instance.
This way, the instance is destroyed exactly once, and the library stays loaded until it’s no longer needed.
Safety is important
There’s one thing worth mentioning before using this in a real application.
Plugins are native code running with the same permissions as the host application.
libloading doesn’t provide any sandboxing. A malicious or buggy plugin can access the same files, memory, and system resources as the application itself.
There are also some important rules around Rust’s extern "C" boundary. For example, a panic that crosses this boundary will abort the process.
The API version check only makes sure that the host and plugin agree on the interface. It doesn’t make an untrusted plugin safe.
Only load plugins you trust.
The unsafe blocks in the host are there because Rust can’t guarantee that everything is safe across this boundary. We need to make sure that the pointers, memory, and function calls are used correctly.
Putting it all together
We’ve built a plugin system in two steps.
The first version showed the basic idea: expose a C-compatible function from a shared library and load it using libloading.
The second version builds on that idea and makes it easier to maintain:
- A shared API crate keeps the interface in one place.
- A function table allows us to use normal Rust traits without passing them across the library boundary.
- API versioning helps the host detect incompatible plugins.
- Pointer-and-length strings make passing text easier.
LoadedPluginmanages the plugin instance and library lifetime.
Both versions are available in the rust-plugin-example repository.
The main branch contains the simple version, while plugin-module contains the three-crate workspace.
You can start with the simple version and add the extra pieces as your plugin system grows.
