Skip to content

Commit aee9796

Browse files
committed
implemented with winapi
1 parent 78c0f7b commit aee9796

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

stdlib/src/lib.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ mod cmath;
1212
mod contextvars;
1313
mod csv;
1414
mod dis;
15+
#[cfg(windows)]
16+
mod win32api;
1517
mod gc;
1618
mod hashlib;
1719
mod json;
@@ -133,6 +135,11 @@ pub fn get_module_inits() -> impl Iterator<Item = (Cow<'static, str>, StdlibInit
133135
{
134136
"_bz2" => bz2::make_module,
135137
}
138+
// Windoes-only
139+
#[cfg(windows)]
140+
{
141+
"win32api" => win32api::make_module,
142+
}
136143
// Unix-only
137144
#[cfg(unix)]
138145
{

stdlib/src/win32api.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
pub(crate) use win32api::make_module;
2+
3+
#[pymodule]
4+
mod win32api {
5+
use crate::vm::{
6+
builtins::{PyStrRef},
7+
function::{},
8+
PyResult,
9+
};
10+
11+
use winapi::shared::minwindef::HINSTANCE__;
12+
use winapi::um::libloaderapi::{LoadLibraryW, GetModuleFileNameW};
13+
14+
const MAX_PATH: usize = 260;
15+
16+
#[pyfunction]
17+
fn LoadLibrary(path: PyStrRef) -> PyResult<usize> {
18+
let lp_caption = to_wstring(path.as_str());
19+
let handle = unsafe {
20+
LoadLibraryW(lp_caption.as_ptr())
21+
} as usize;
22+
23+
Ok(handle)
24+
}
25+
26+
#[pyfunction]
27+
fn GetModuleFileName(handle: usize) -> String {
28+
let mut path: Vec<u16> = vec![0; MAX_PATH];
29+
30+
let length = unsafe {
31+
GetModuleFileNameW(handle as *mut HINSTANCE__, path.as_mut_ptr(), MAX_PATH as u32)
32+
};
33+
34+
if length == 0 {
35+
// error
36+
}
37+
38+
let (path, _) = path.split_at(length as usize);
39+
String::from_utf16(&path).unwrap()
40+
}
41+
42+
#[cfg(windows)]
43+
// Get win32 lpstr from &str, converting u8 to u16 and appending '\0'
44+
// See retep998's traits for a more general solution: https://users.rust-lang.org/t/tidy-pattern-to-work-with-lpstr-mutable-char-array/2976/2
45+
fn to_wstring(value: &str) -> Vec<u16> {
46+
use std::os::windows::ffi::OsStrExt;
47+
48+
std::ffi::OsStr::new(value)
49+
.encode_wide()
50+
.chain(std::iter::once(0))
51+
.collect()
52+
}
53+
}

0 commit comments

Comments
 (0)