use e_utils::Result;
use libloading::Library;
use std::{ffi::OsStr, path::PathBuf};
pub fn load_library<S>(dll_path: S) -> Result<Library>
where
S: AsRef<OsStr>,
{
unsafe { libloading::Library::new(dll_path) }.map_err(|e| e.to_string().into())
}
#[derive(Default, Debug)]
pub struct Lib {
lib_path: PathBuf,
lib: Option<Library>,
}
unsafe impl Send for Lib {}
unsafe impl Sync for Lib {}
impl Lib {
pub fn new(lib_path: PathBuf) -> Self {
let lib = load_library(lib_path.clone()).ok();
Self { lib_path, lib }
}
pub fn set_lib(&mut self, lib: Option<Library>) {
self.lib = lib
}
pub fn set_path(&mut self, path: PathBuf) {
self.lib_path = path
}
pub fn free(&mut self) -> Option<()> {
self.lib.take()?.close().ok()
}
}
impl Lib {
pub fn get(&self) -> &Library {
self
.lib
.as_ref()
.expect(&format!("{} 链接库无法找到", self.lib_path.display(),))
}
pub fn get_mut(&mut self) -> &mut Library {
self
.lib
.as_mut()
.expect(&format!("{} 链接库无法找到", self.lib_path.display(),))
}
pub fn get_path(&self) -> PathBuf {
self.lib_path.clone()
}
}