Michael-F-Bryan / rust-ffi-guide

A guide for doing FFI using Rust
https://michael-f-bryan.github.io/rust-ffi-guide/
Creative Commons Zero v1.0 Universal
282 stars 18 forks source link

Dynamic Loading Chapter #45

Closed Michael-F-Bryan closed 6 years ago

Michael-F-Bryan commented 6 years ago

I've started work on a dynamic library loading chapter. The idea is to allow users to create plugins for our app and then load them at runtime by specifying the path to some shared library.

The general idea is:

The end goal is to allow users to provide a shared library (DLL, *.so, etc) which contains a set of pre-defined functions. These functions will then allow us to manipulate a request before it is sent and then manipulate/inspect the response before displaying it to the user.

From the Rust side of things, by far the easiest way to establish this is to define a Plugin trait which does the various manipulations, then add in a macro users can run which will define all the unsafe function declarations.

Our Plugin trait may look something like this:

pub trait Plugin {
    fn before_send(&mut self, request: &mut Request) {
        // noop default
    }

    fn on_receive(&mut self, response: &mut Response) {
        // noop default
    }
}

The macro would then declare an extern "C" constructor which exports a trait object (Box<Plugin>) with some pre-defined symbol (e.g. "plugin_create()`).

TODO: Steal a bunch of stuff from the dynamic loading page of the original guide to show how you'd do dynamic loading on a trivial project. Then extend it to work with our client library.