I am writing a / FFI wrapper for a C library that requires a global initialization call in the main thread, as well as for destruction.
This is how I process it now:
struct App; impl App { fn init() -> Self { unsafe { ffi::InitializeMyCLib(); } App } } impl Drop for App { fn drop(&mut self) { unsafe { ffi::DestroyMyCLib(); } } }
which can be used as:
fn main() { let _init_ = App::init();
This works fine, but it seems like a hack, tying these challenges to a life of an unnecessary structure. Having a destructor in a finally (Java) or at_exit (Ruby) block seems to be theoretically more appropriate.
Is there an even more elegant way to do this in Rust?
EDIT
Is it possible / safe to use this setting like this (using the lazy_static box) instead of the second block above:
lazy_static! { static ref APP: App = App::new(); }
Is it possible to guarantee that this link will be initialized before any other code and destroyed upon exit? Is it wrong to use the lazy_static library in the library?
It would also facilitate facilitating access to FFI through this single structure, since I would not have to go past the reference to the instance structure (called _init_ in my original example).
This will also make it safer since I could make the App constru default default constructor.
source share