opencl_dynamic_sys/container/
utils.rs

1use std::sync::OnceLock;
2
3use dlopen2::{wrapper::Container, Error};
4
5use super::OpenCl;
6
7/// `dlopen2` container with all loaded API functions.
8pub type OpenClRuntime = Container<OpenCl>;
9
10static OPENCL_RUNTIME: OnceLock<Result<OpenClRuntime, Error>> = OnceLock::new();
11
12/// Utility function to load the OpenCL shared library (actual load will be performed only once).
13/// Returns an error if the library is not found.
14pub fn load_library() -> &'static Result<OpenClRuntime, Error> {
15    OPENCL_RUNTIME.get_or_init(|| {
16        if let Ok(env_var) = std::env::var("OPENCL_DYLIB_PATH") {
17            for library_path in env_var.split(';') {
18                let library = unsafe { Container::load(library_path) };
19                if library.is_ok() {
20                    return library;
21                }
22            }
23        }
24
25        const LIBRARY_NAME: &'static str = if cfg!(target_os = "windows") {
26            "OpenCL.dll"
27        } else if cfg!(target_os = "macos") {
28            "/System/Library/Frameworks/OpenCL.framework/OpenCL"
29        } else {
30            "libOpenCL.so"
31        };
32
33        unsafe { Container::load(LIBRARY_NAME) }
34    })
35}
36
37/// Utility function to check if the OpenCL shared library is loaded successfully.
38pub fn is_opencl_runtime_available() -> bool {
39    load_library().is_ok()
40}