use std::{ffi::c_void, path::Path};
pub struct Library {
handle: *mut c_void,
}
unsafe impl Send for Library {}
unsafe impl Sync for Library {}
impl Library {
pub fn open(path: &Path) -> Result<Self, String> {
let handle = imp::open(path)?;
Ok(Self { handle })
}
pub fn symbol(&self, name: &str) -> Option<*mut c_void> {
imp::symbol(self.handle, name)
}
}
impl Drop for Library {
fn drop(&mut self) {
imp::close(self.handle);
}
}
#[cfg(unix)]
mod imp {
use std::{
ffi::{CStr, CString, c_char, c_void},
os::unix::ffi::OsStrExt as _,
path::Path,
};
pub fn open(path: &Path) -> Result<*mut c_void, String> {
let name = CString::new(path.as_os_str().as_bytes())
.map_err(|_| "path contains a NUL byte".to_string())?;
let handle = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW) };
if handle.is_null() {
return Err(last_error());
}
Ok(handle)
}
pub fn symbol(handle: *mut c_void, name: &str) -> Option<*mut c_void> {
let name = CString::new(name).ok()?;
let sym = unsafe { libc::dlsym(handle, name.as_ptr()) };
(!sym.is_null()).then_some(sym)
}
pub fn close(handle: *mut c_void) {
unsafe { libc::dlclose(handle) };
}
fn last_error() -> String {
let msg = unsafe { libc::dlerror() };
if msg.is_null() {
return "unknown error".to_string();
}
let text = unsafe { CStr::from_ptr(msg.cast::<c_char>()) };
String::from_utf8_lossy(text.to_bytes()).into_owned()
}
}
#[cfg(windows)]
mod imp {
use std::{
ffi::{CString, c_char, c_void},
path::Path,
};
unsafe extern "system" {
fn LoadLibraryA(name: *const c_char) -> *mut c_void;
fn GetProcAddress(
module: *mut c_void,
name: *const c_char,
) -> *mut c_void;
fn FreeLibrary(module: *mut c_void) -> i32;
fn GetLastError() -> u32;
}
pub fn open(path: &Path) -> Result<*mut c_void, String> {
let text = path
.to_str()
.ok_or_else(|| "path is not valid UTF-8".to_string())?;
let name = CString::new(text)
.map_err(|_| "path contains a NUL byte".to_string())?;
let handle = unsafe { LoadLibraryA(name.as_ptr()) };
if handle.is_null() {
let code = unsafe { GetLastError() };
return Err(format!("LoadLibrary failed with error {code}"));
}
Ok(handle)
}
pub fn symbol(handle: *mut c_void, name: &str) -> Option<*mut c_void> {
let name = CString::new(name).ok()?;
let sym = unsafe { GetProcAddress(handle, name.as_ptr()) };
(!sym.is_null()).then_some(sym)
}
pub fn close(handle: *mut c_void) {
unsafe { FreeLibrary(handle) };
}
}