]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/dynamic_lib.rs
std: Clean out deprecated APIs
[rust.git] / src / libstd / sys / windows / dynamic_lib.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12 use os::windows::prelude::*;
13
14 use ffi::{CString, OsStr};
15 use io;
16 use sys::c;
17
18 pub struct DynamicLibrary {
19     handle: c::HMODULE,
20 }
21
22 impl DynamicLibrary {
23     pub fn open(filename: &str) -> io::Result<DynamicLibrary> {
24         let filename = OsStr::new(filename)
25                              .encode_wide()
26                              .chain(Some(0))
27                              .collect::<Vec<_>>();
28         let result = unsafe {
29             c::LoadLibraryW(filename.as_ptr())
30         };
31         if result.is_null() {
32             Err(io::Error::last_os_error())
33         } else {
34             Ok(DynamicLibrary { handle: result })
35         }
36     }
37
38     pub fn symbol(&self, symbol: &str) -> io::Result<usize> {
39         let symbol = try!(CString::new(symbol));
40         unsafe {
41             match c::GetProcAddress(self.handle, symbol.as_ptr()) as usize {
42                 0 => Err(io::Error::last_os_error()),
43                 n => Ok(n),
44             }
45         }
46     }
47 }
48
49 impl Drop for DynamicLibrary {
50     fn drop(&mut self) {
51         unsafe {
52             c::FreeLibrary(self.handle);
53         }
54     }
55 }