1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#[cfg(windows)]
use winapi::{
shared::minwindef::HMODULE,
um::libloaderapi::{FreeLibrary, GetProcAddress, LoadLibraryA},
};
#[cfg(unix)]
use libc::{dlclose, dlopen, dlsym};
use std::ffi::CString;
use std::os::raw::c_void;
#[derive(Clone, Debug)]
pub struct SharedObject {
#[cfg(windows)]
handle: HMODULE,
#[cfg(unix)]
handle: *mut c_void,
}
impl SharedObject {
#[cfg(windows)]
pub fn load<T>(path: T) -> Self
where
T: AsRef<str>,
{
let cstr = CString::new(path.as_ref()).expect("opengl32.dll");
Self {
handle: unsafe { LoadLibraryA(cstr.as_ptr()) },
}
}
#[cfg(unix)]
pub fn load<T>(path: T) -> Self
where
T: AsRef<str>,
{
let cstr = CString::new(path.as_ref()).expect("libEGL.so");
Self {
handle: unsafe { dlopen(cstr.as_ptr(), 2) },
}
}
pub fn get_proc_address<T>(&self, name: T) -> *const c_void
where
T: AsRef<str>,
{
let cstr = CString::new(name.as_ref()).unwrap();
#[cfg(windows)]
unsafe {
GetProcAddress(self.handle, cstr.as_ptr()) as *const c_void
}
#[cfg(unix)]
unsafe {
dlsym(self.handle, cstr.as_ptr())
}
}
}
impl Drop for SharedObject {
fn drop(&mut self) {
if self.handle.is_null() {
unsafe {
#[cfg(windows)]
FreeLibrary(self.handle);
#[cfg(unix)]
dlclose(self.handle);
}
self.handle = std::ptr::null_mut();
}
}
}