glib_win32/functions.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2#[cfg(windows)]
3use glib::translate::*;
4#[cfg(windows)]
5use std::path::PathBuf;
6
7#[cfg(windows)]
8use crate::ffi;
9
10#[doc(alias = "g_win32_get_package_installation_directory_of_module")]
11#[doc(alias = "get_package_installation_directory_of_module")]
12#[cfg(all(docsrs, windows))]
13pub fn package_installation_directory_of_module(
14 hmodule: std::os::windows::raw::HANDLE,
15) -> Result<PathBuf, std::io::Error> {
16 // # Safety
17 // The underlying `GetModuleFilenameW` function has three possible
18 // outcomes when a raw pointer get passed to it:
19 // - When the pointer is a valid HINSTANCE of a DLL (e.g. acquired
20 // through the `GetModuleHandleW`), it sets a file path to the
21 // assigned "out" buffer and sets the return value to be the length
22 // of said path string
23 // - When the pointer is null, it sets the full path of the process'
24 // executable binary to the assigned buffer and sets the return value
25 // to be the length of said string
26 // - Whenever the provided buffer size is too small, it will set a
27 // truncated version of the path and return the length of said string
28 // while also setting the thread-local last-error code to
29 // `ERROR_INSUFFICIENT_BUFFER` (evaluates to 0x7A)
30 // - When the pointer is not a valid HINSTANCE that isn't NULL (e.g.
31 // a pointer to some GKeyFile), it will return 0 and set the last-error
32 // code to `ERROR_MOD_NOT_FOUND` (evaluates to 0x7E)
33 //
34 // The `g_win32_get_package_installation_directory_of_module` already
35 // handles all of the outcomes gracefully by:
36 // - Preallocating a MAX_PATH-long array of wchar_t for the out buffer,
37 // so that outcome #3 can be safely assumed to never happen
38 // - Returning NULL when outcome #4 happens
39 match unsafe {
40 from_glib_full::<_, Option<PathBuf>>(
41 ffi::g_win32_get_package_installation_directory_of_module(hmodule),
42 )
43 } {
44 Some(pb) => Ok(pb),
45 None => Err(std::io::Error::last_os_error()),
46 }
47}