Last active
December 17, 2023 15:09
-
-
Save lededev/4fd997ff1dfa9c320ada62ca6ee0d7f5 to your computer and use it in GitHub Desktop.
Rust(unsafe) 结构体转指针通过LPARAM / usize参数传递
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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