如何存储引用而不必处理生命周期?

Mar*_*tti 3 symbols ffi lifetime rust

由于所建议dynamic_reload板条箱的例子,我收集Symbols,而不是每次都提取它们,但Symbol需要一辈子.使用生命周期更改方法签名并破坏与方法的兼容性DynamicReload::update.

用它std::mem::transmute来改变Symbol生命周期是一种有效的解决方法'static吗?

extern crate dynamic_reload;

use dynamic_reload::{DynamicReload, Lib, Symbol, Search, PlatformName, UpdateState};
use std::sync::Arc;
use std::time::Duration;
use std::thread;
use std::mem::transmute;

struct Plugins {
    plugins: Vec<(Arc<Lib>, Arc<Symbol<'static, extern "C" fn() -> i32>>)>,
}

impl Plugins {
    fn add_plugin(&mut self, plugin: &Arc<Lib>) {
        match unsafe { plugin.lib.get(b"shared_fun\0") } {
            Ok(temp) => {
                let f: Symbol<extern "C" fn() -> i32> = temp;
                self.plugins.push((plugin.clone(), Arc::new(unsafe { transmute(f) })));
            },
            Err(e) => println!("Failed to load symbol: {:?}", e),
        }
    }

    fn unload_plugins(&mut self, lib: &Arc<Lib>) {
        for i in (0..self.plugins.len()).rev() {
            if &self.plugins[i].0 == lib {
                self.plugins.swap_remove(i);
            }
        }
    }

    fn reload_plugin(&mut self, lib: &Arc<Lib>) {
        Self::add_plugin(self, lib);
    }

    // called when a lib needs to be reloaded.
    fn reload_callback(&mut self, state: UpdateState, lib: Option<&Arc<Lib>>) {
        match state {
            UpdateState::Before => Self::unload_plugins(self, lib.unwrap()),
            UpdateState::After => Self::reload_plugin(self, lib.unwrap()),
            UpdateState::ReloadFailed(_) => println!("Failed to reload"),
        }
    }
}

fn main() {
    let mut plugs = Plugins { plugins: Vec::new() };

    // Setup the reload handler. A temporary directory will be created inside the target/debug
    // where plugins will be loaded from. That is because on some OS:es loading a shared lib
    // will lock the file so we can't overwrite it so this works around that issue.
    let mut reload_handler = DynamicReload::new(Some(vec!["target/debug"]),
                                                Some("target/debug"),
                                                Search::Default);

    // test_shared is generated in build.rs
    match reload_handler.add_library("test_shared", PlatformName::Yes) {
        Ok(lib) => plugs.add_plugin(&lib),
        Err(e) => {
            println!("Unable to load dynamic lib, err {:?}", e);
            return;
        }
    }

    //
    // While this is running (printing a number) change return value in file src/test_shared.rs
    // build the project with cargo build and notice that this code will now return the new value
    //
    loop {
        reload_handler.update(Plugins::reload_callback, &mut plugs);

        if plugs.plugins.len() > 0 {
            let fun = &plugs.plugins[0].1;
            println!("Value {}", fun());
        }

        // Wait for 0.5 sec
        thread::sleep(Duration::from_millis(500));
    }
}
Run Code Online (Sandbox Code Playgroud)

我仍然需要保持Arc<Lib>在向量内,因为Symbol没有实现PartialEq.

She*_*ter 6

如何存储引用而不必处理生命周期?

98%的案例的答案是:你没有.生命周期是使用Rust的最大原因之一.生命周期在编译时强制执行引用将始终引用有效的内容.如果你想"忽略"生命周期,那么Rust可能不是实现特定设计的最佳语言.您可能需要选择其他语言或设计.

用它std::mem::transmute来改变Symbol生命周期是一种有效的解决方法'static吗?

transmute是大锤子,适合各种好的和坏的想法和实施.我鼓励永远不要直接使用它,而是将它包装在一个抽象层中,以某种方式帮助你强制执行适当的限制,使特定的transmute正确.

如果您选择使用transmute,则承担编译器以前的全部责任.由您决定引用始终有效,否则您将调用未定义的行为,并允许您的程序执行任何数量的非常糟糕的事情.


对于您的特定情况,您可以使用Rental crate在一个隐藏Symbols 生命周期的结构中保留"库"和"库中的引用" .事实上,Rental使用libloading作为激励示例,libloading支持dynamic_reload.请参阅 为什么我不能在同一个结构中存储值和对该值的引用?了解更多细节和陷阱.

我不乐观这会起作用,因为DynamicReload::update需要一个&mut self.在该方法调用期间,它可能很容易使所有现有引用无效.

也可以看看: