Skip to content

Instantly share code, notes, and snippets.

@lededev
Last active December 17, 2023 15:09
Show Gist options
  • Save lededev/4fd997ff1dfa9c320ada62ca6ee0d7f5 to your computer and use it in GitHub Desktop.
Save lededev/4fd997ff1dfa9c320ada62ca6ee0d7f5 to your computer and use it in GitHub Desktop.
Rust(unsafe) 结构体转指针通过LPARAM / usize参数传递
struct InOutData {
pid: u32, // in
hwnd: HWND // out
}
unsafe extern "system" fn callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
let s: &mut InOutData = mem::transmute(lparam); // LPARAM转回结构体指针
if ((*s).pid == GetWindowThreadProcessId(hwnd, Some(ptr::null_mut()))) {
(*s).hwnd = hwnd;
return false.into();
}
return true.into();
}
fn sender() {
let mut parm = InOutData {0x1234567A, HWND(0)};
unsafe { // 将结构体指针转为LPARAM 或者 usize,两者的内存占用必须一致
EnumWindows(Some(callback), LPARAM(mem::transmute(&mut parm))).unwrap();
}
// 如果hwnd被回调函数修改过,这里能看到非零句柄值
println!("HWND: {:?}, PID: {}", parm.hwnd, parm.pid);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment