hot-lib-reloader
A simple crate around libloading that can be used to watch Rust libraries (dylibs) and will reload them again when they have changed. Useful for changing code and seeing the effects without having to restart the app.

Note: This is meant to be used for development! Don't use it in production!
Also currently proc_macro::Span is required and you will need to run hot-reloadable code with Rust nightly.
What it does
-
Watch a dynamically loadable library you specify, reload it when it changes.
-
Generates a type that provides methods to dynamically call the functions exposed by that library. You specify Rust source files that contain functions exported in the library above.
hot-lib-reloaderwill parse those, find those functions and their signatures and use it to create methods you can call (instead of manually having to query for a library symbol).
For a detailed discussion see https://robert.kra.hn/posts/hot-reloading-rust/.
Usage
Assuming you use a workspace with the following layout:
├── Cargo.toml
└── src
│ └── main.rs
└── lib
├── Cargo.toml
└── src
└── lib.rs
lib
The library should expose functions and state. It should have specify dylib as crate type. The ./lib/Cargo.toml:
[]
= "lib"
= "0.1.0"
= "2021"
[]
= ["rlib", "dylib"]
And ./lib/lib.rs
bin
In the binary, use the lib and lot hot-lib-reloader. ./Cargo.toml:
[]
= "2"
= ["lib"]
[]
= "bin"
= "0.1.0"
= "2021"
[]
= "^0.4"
= { = "lib" }
You can then define and use the lib reloader like so (./src/main.rs):
define_lib_reloader!
Above is the part that matters: A new type MyLibLoader is created that provides a method MyLibLoader::do_stuff(&self).
The method is automatically generated from lib::do_stuff().
Indeed, if we were to add a method lib::add_numbers(a: i32, b: i32) -> i32, a method MyLibLoader::add_numbers(&self, a: i32, b: i32) -> i32 would be generated. Etc.
Note: If you prefer to not use macros, the macro-free version of the code above is:
use LibReloader;
Running it
To start compilation of the library:
cargo watch -w lib -x build
And in addition to that start compilation of the binary with reload enabled:
cargo watch -w bin -x run
A change that you now make to lib/lib.rs will have an immediate effect on the app.
More examples
Examples can be found at rksm/hot-lib-reloader-rs/examples.
- minimal: Bare-bones setup.
- reload-feature: Use a feature to switch between dynamic and static version.
- bevy: Shows how to hot-reload bevy systems.
License: MIT