Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.20 KB | None | 0 0
  1. // ./plugins/foo/src/lib.rs
  2. use host::*;
  3. use host::Plugin;
  4.  
  5. #[derive(Debug, Default)]
  6. pub struct Foo;
  7.  
  8. impl Plugin for Foo {
  9.     fn name(&self) -> &'static str {
  10.         "foo"
  11.     }
  12. }
  13. declare_plugin!(Foo, Foo::default);
  14.  
  15. // ./host/src/main.rs
  16. use libloading::{Library, Symbol};
  17. mod plugins;
  18. use plugins::*;
  19.  
  20. type Constructor = unsafe fn() -> *mut Plugin;
  21. fn main() {
  22.     let lib = Library::new("foo").unwrap();
  23.     unsafe {
  24.         let func: Symbol<Constructor> = lib.get(b"_plugin_create").unwrap();
  25.         let raw = func();
  26.         let plugin = Box::from_raw(raw);
  27.         println!("7 + 42 = {}", plugin.name());
  28.     }
  29. }
  30.  
  31.  
  32. // ./host/src/lib.rs
  33. mod plugins;
  34. pub use plugins::*;
  35.  
  36. // ./host/src/plugins.rs
  37. #[macro_export]
  38. macro_rules! declare_plugin {
  39.    ($plugin_type:ty, $constructor:path) => {
  40.        #[no_mangle]
  41.        pub extern "C" fn _plugin_create() -> *mut $crate::Plugin {
  42.            // make sure the constructor is the correct type.
  43.            let constructor: fn() -> $plugin_type = $constructor;
  44.  
  45.            let object = constructor();
  46.            let boxed: Box<$crate::Plugin> = Box::new(object);
  47.            Box::into_raw(boxed)
  48.        }
  49.    };
  50. }
  51.  
  52. pub trait Plugin {
  53.     fn name(&self) -> &'static str;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement