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