I'm currently working on a Rust project where I need to use the winapi
crate to allocate memory. However, I'm encountering issues with importing certain modules and functions from winapi
. Here is a snippet of my Cargo.toml
and main.rs
:
[package]
name = "loader"
version = "0.1.0"
edition = "2021"
[dependencies]
sysinfo = "0.30.13"
winapi = { version = "0.3.9", features = [
"winuser",
"winbase",
"synchapi",
"processthreadsapi",
"memoryapi",
"handleapi",
"tlhelp32",
"winnt",
"minwinbase"
] }
use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE};
use winapi::um::memoryapi::{VirtualAlloc, VirtualProtect};
use winapi::um::processthreadsapi::CreateThread;
use winapi::um::minwinbase::LPTHREAD_START_ROUTINE;
use std::ptr;
fn main() { ... }
Despite following the documentation and examples, I keep getting errors like "could not find um
in winapi
". I've ensured that the necessary features are enabled in Cargo.toml
, but the issue persists.
I'm using rustc 1.81
Could anyone provide guidance on what might be going wrong or suggest any changes I should make to resolve these import errors?
Thank you in advance for your help!
I found the solution to this issue through this helpful Stack Overflow answer. Here's what worked for me:
First, I updated my Cargo.toml
file with the necessary features to use winapi
:
[target.'cfg(windows)'.dependencies]
winapi = {
version = "0.3.9",
features = [
"winnt",
"winuser",
"winbase",
"synchapi",
"processthreadsapi",
"memoryapi",
"handleapi",
"tlhelp32",
"minwinbase"
]
}
Since Iām using Linux as my development environment, I set up cross-compilation for Windows by following these steps:
Add the Windows target: rustup target add x86_64-pc-windows-gnu
Install mingw for compile Windows on Linux : sudo apt-get install mingw-w64
and then for build.
cargo build --target x86_64-pc-windows-gnu
2 Likes
You might have reason to use winapi
specifically, but if not you should be aware that it's soft deprecated in favor of the windows
crate, which is generated from metadata so has much better coverage, has nicer error handling, etc, but relevantly here, has better features, that more obviously follow a logical package structure and have better dependencies, and has a feature search that tells you what features each API requires exactly:
For example, GlobalAlloc
requires only Win32_System_Memory
.
Also, googling suggests you can apparently configure rust analyzer with the desired target with rust-analyzer.cargo.target
, but I can't check that right now, sorry!
2 Likes