gpt4 book ai didi

dynamic - 如何在Rust中清除libloading的内部缓存

转载 作者:行者123 更新时间:2023-12-03 11:48:50 26 4
gpt4 key购买 nike

如标题所示。对于具有相同路径的库,在libloading中似乎有一个内部缓存。我将如何清除它或从中丢弃物品。

以下mwe

use libloading::{Library, Symbol};
use std::process::Command;

fn write(i: i64) {
std::fs::write("source.rs", format!("
#[no_mangle]
pub extern \"C\" fn fun() {{
println!(\"{}\");
}}", i)).expect("write error");
}

fn compile() {
Command::new("rustc")
.arg("--crate-type")
.arg("cdylib")
.arg("source.rs")
.arg("-o")
.arg("binary.o")
.output()
.expect("compile error");
}

fn run() {
let lib = Library::new("./binary.o").unwrap();

unsafe {
lib.get::<Symbol<unsafe extern "C" fn()>>(b"fun").unwrap()()
}
}

fn main() {
for i in 0..10 {
write(i);
compile();
run();
}
}

退货
0
0
0
...

但是我想要
0
1
2
...

最佳答案

我最终重新发明了轮子。如果有人偶然发现相同的问题:

use libc;

use std::ffi::CStr;
use std::mem::transmute;

pub struct SharedLib {
handle: *mut libc::c_void,
}

impl SharedLib {
pub fn new(path: &str) -> Self {
let path = CStr::from_bytes_with_nul(path.as_bytes()).unwrap();
let handle = unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_NOW) };

SharedLib {
handle: handle,
}
}

pub fn run<T>(&self, name: &str) -> T {
if self.handle.is_null() {
panic!("error");
}

let name = CStr::from_bytes_with_nul(name.as_bytes()).unwrap();
unsafe {
let ptr = libc::dlsym(self.handle, name.as_ptr());
transmute::<_, fn() -> T>(ptr)()
}
}
}

impl Drop for SharedLib {
fn drop(&mut self) {
unsafe {
libc::dlclose(self.handle);
}
}
}

关于dynamic - 如何在Rust中清除libloading的内部缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61952542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com