]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/dynamic_lib.rs
Rollup merge of #60429 - estebank:pub-path, r=michaelwoerister
[rust.git] / src / libstd / sys / windows / dynamic_lib.rs
1 use crate::os::windows::prelude::*;
2
3 use crate::ffi::{CString, OsStr};
4 use crate::io;
5 use crate::sys::c;
6
7 pub struct DynamicLibrary {
8     handle: c::HMODULE,
9 }
10
11 impl DynamicLibrary {
12     pub fn open(filename: &str) -> io::Result<DynamicLibrary> {
13         let filename = OsStr::new(filename)
14                              .encode_wide()
15                              .chain(Some(0))
16                              .collect::<Vec<_>>();
17         let result = unsafe {
18             c::LoadLibraryW(filename.as_ptr())
19         };
20         if result.is_null() {
21             Err(io::Error::last_os_error())
22         } else {
23             Ok(DynamicLibrary { handle: result })
24         }
25     }
26
27     pub fn symbol(&self, symbol: &str) -> io::Result<usize> {
28         let symbol = CString::new(symbol)?;
29         unsafe {
30             match c::GetProcAddress(self.handle, symbol.as_ptr()) as usize {
31                 0 => Err(io::Error::last_os_error()),
32                 n => Ok(n),
33             }
34         }
35     }
36 }
37
38 impl Drop for DynamicLibrary {
39     fn drop(&mut self) {
40         unsafe {
41             c::FreeLibrary(self.handle);
42         }
43     }
44 }