Skip to main content

dtlvnative_sys/
runtime.rs

1use std::{env, path::PathBuf};
2
3/// Directory containing optional runtime libraries and their bundled OpenMP
4/// dependency. Deploy these together and set DTLVNATIVE_RUNTIME_DIR when moving
5/// an application away from its Cargo build directory.
6pub fn directory() -> PathBuf {
7    env::var_os("DTLVNATIVE_RUNTIME_DIR")
8        .map(PathBuf::from)
9        .unwrap_or_else(|| PathBuf::from(env!("DTLVNATIVE_RUNTIME_DIR")))
10}
11
12pub(crate) fn load(name: &str) -> Result<libloading::Library, String> {
13    let path = std::path::absolute(directory().join(name)).map_err(|error| error.to_string())?;
14    // SAFETY: These are the versioned runtime artifacts selected by build.rs.
15    // The deployment override must contain the same trusted native libraries.
16    // Handles are retained by the API's OnceLock for the life of the process.
17    unsafe {
18        #[cfg(windows)]
19        let result = libloading::os::windows::Library::load_with_flags(
20            &path,
21            libloading::os::windows::LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
22                | libloading::os::windows::LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
23        )
24        .map(libloading::Library::from);
25        #[cfg(not(windows))]
26        let result = libloading::Library::new(&path);
27        result.map_err(|error| format!("Could not load {}: {error}. Deploy the runtime and its bundled OpenMP library together and set DTLVNATIVE_RUNTIME_DIR.", path.display()))
28    }
29}