Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ./plugins/foo/src/lib.rs
- use host::*;
- use host::Plugin;
- #[derive(Debug, Default)]
- pub struct Foo;
- impl Plugin for Foo {
- fn name(&self) -> &'static str {
- "foo"
- }
- }
- declare_plugin!(Foo, Foo::default);
- // ./host/src/main.rs
- use libloading::{Library, Symbol};
- mod plugins;
- use plugins::*;
- type Constructor = unsafe fn() -> *mut Plugin;
- fn main() {
- let lib = Library::new("foo").unwrap();
- unsafe {
- let func: Symbol<Constructor> = lib.get(b"_plugin_create").unwrap();
- let raw = func();
- let plugin = Box::from_raw(raw);
- println!("7 + 42 = {}", plugin.name());
- }
- }
- // ./host/src/lib.rs
- mod plugins;
- pub use plugins::*;
- // ./host/src/plugins.rs
- #[macro_export]
- macro_rules! declare_plugin {
- ($plugin_type:ty, $constructor:path) => {
- #[no_mangle]
- pub extern "C" fn _plugin_create() -> *mut $crate::Plugin {
- // make sure the constructor is the correct type.
- let constructor: fn() -> $plugin_type = $constructor;
- let object = constructor();
- let boxed: Box<$crate::Plugin> = Box::new(object);
- Box::into_raw(boxed)
- }
- };
- }
- pub trait Plugin {
- fn name(&self) -> &'static str;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement