Struggling with static lifetimes and borrowed values

Hi all

I am trying to have a lazy_static module-level constant for a "libloading" symbol (it is either assigned once and never changes, or the program panics and terminates; so static symbol seems to be a good thing)

However, I struggle to properly initialize it:

I have a type alias for the DLL symbol as follows:

extern crate libloading as dll;
pub type SynthFn<'lib> = dll::Symbol<'lib, unsafe extern "stdcall" fn(dt::PChar, dt::Integer, dt::Integer, &mut [SynthFormSet], dt::Integer) -> dt::Integer>;

then I have static initalization block:

lazy_static! {
   static ref SYNTH_DLL: dll::Library = initialize_dll();
   static ref SYNTHESIZE_FN: SynthFn = initialize_dll_fn();
}

and here're the function definitions:

fn initialize_dll() -> dll::Library {
    match dll::Library::new("fmsynth.dll") {
        Ok(lib) => lib,
        Err(_) => panic!("DLL not loaded")
    }
}

fn initialize_dll_fn() -> SynthFn {
    unsafe {
        match SYNTH_DLL.get(b"SynthesizeForms") {
            Ok(fun) => {
                fun
            }
            Err(_) => panic!("Function not found!")
        }
    }
}

I've tried like .. tens of combinations for specifiyng lifetimes, etc. however I was not able to achieve any meaningful progress. I suspect that a lot of factors are in play here, so will be very happy if anyone helps me figure them out. The current set of compile errors looks as follows:

error[E0106]: missing lifetime specifier
--> src\synthesis.rs:49:27
|
49 | fn initialize_dll_fn() -> SynthFn {
| ^^^^^^^ help: consider giving it a 'static lifetime: SynthFn + 'static
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from

error[E0106]: missing lifetime specifier
--> src\synthesis.rs:14:31
|
14 | static ref SYNTHESIZE_FN: SynthFn = initialize_dll_fn();
| ^^^^^^^ expected lifetime parameter

error[E0106]: missing lifetime specifier
--> src\synthesis.rs:14:31
|
14 | static ref SYNTHESIZE_FN: SynthFn = initialize_dll_fn();
| ^^^^^^^ help: consider giving it a 'static lifetime: SynthFn + 'static
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from

(just to clarify: I've tried to apply those suggestions, but no luck at all.. all hell breaks loose anyway)

Try adding 'static in the following places:

lazy_static! {
   ...
   static ref SYNTHESIZE_FN: SynthFn<'static> = initialize_dll_fn();
}

fn initialize_dll_fn() -> SynthFn<'static> {
   ... same as you have it
}
1 Like

that's so cool !! Saved me lot of pain! Now I've even refactored DLL symbol initialization into separate mod and generalized so I can consume it from any other module with minimal hassle! Yikes !

PS: I really believe some compiler hints and doc/book could be improved still..

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.