我正在使用Rust中的WinAPI,并且有一些函数(如
EnumWindows())需要回调.回调通常接受一个额外的参数(类型为LPARAM,它是i64的别名),您可以使用它将一些自定义数据传递给回调.
我已经发送了Vec< T>对象作为LPARAM到WinAPI回调,它工作正常.例如,将“pparam”值“解包”到Vec< RECT>.在我的情况下看起来像这样:
unsafe extern "system" fn enumerate_callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
let rects = lparam as *mut Vec;
}
我现在必须传递一个闭包,而不是传递一个向量.我不能使用函数指针,因为我的闭包必须捕获一些变量,如果我使用了函数则无法访问它们.在C中,我会使用std :: function<>对于我的特定任务,我认为在Rust中相应的抽象是一个闭包.
我的解包代码如下所示:
unsafe extern "system" fn enumerate_callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
let cb: &mut FnMut(HWND) -> bool = &mut *(lparam as *mut c_void as *mut FnMut(HWND) -> bool);
// ...
}
SSCCE:
use std::os::raw::c_void;
fn enum_wnd_proc(some_value: i32, lparam: i32) {
let closure: &mut FnMut(i32) -> bool =
unsafe { (&mut *(lparam as *mut c_void as *mut FnMut(i32) -> bool)) };
println!("predicate() executed and returned: {}", closure(some_value));
}
fn main() {
let sum = 0;
let mut closure = |some_value: i32| -> bool {
sum += some_value;
sum >= 100
};
let lparam = (&mut closure as *mut c_void as *mut FnMut(i32) -> bool) as i32;
enum_wnd_proc(20, lparam);
}
我收到这些错误:
error[E0277]: expected a `std::ops::FnMut` closure, found `std::ffi::c_void`
--> src/main.rs:5:26
|
5 | unsafe { (&mut *(lparam as *mut c_void as *mut FnMut(i32) -> bool)) };
| ^^^^^^^^^^^^^^^^^^^^^ expected an `FnMut` closure, found `std::ffi::c_void`
|
= help: the trait `std::ops::FnMut` is not implemented for `std::ffi::c_void`
= note: required for the cast to the object type `dyn std::ops::FnMut(i32) -> bool`
error[E0606]: casting `&mut [closure@src/main.rs:12:23: 15:6 sum:_]` as `*mut std::ffi::c_void` is invalid
--> src/main.rs:17:19
|
17 | let lparam = (&mut closure as *mut c_void as *mut FnMut(i32) -> bool) as i32;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0606]: casting `*mut dyn std::ops::FnMut(i32) -> bool` as `i32` is invalid
--> src/main.rs:17:18
|
17 | let lparam = (&mut closure as *mut c_void as *mut FnMut(i32) -> bool) as i32;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: cast through a thin pointer first
error[E0277]: expected a `std::ops::FnMut` closure, found `std::ffi::c_void`
--> src/main.rs:17:19
|
17 | let lparam = (&mut closure as *mut c_void as *mut FnMut(i32) -> bool) as i32;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected an `FnMut` closure, found `std::ffi::c_void`
|
= help: the trait `std::ops::FnMut` is not implemented for `std::ffi::c_void`
= note: required for the cast to the object type `dyn std::ops::FnMut(i32) -> bool`
我想知道:
>有没有办法将函数/闭包传递给不同的函数并执行那些“类C”演员表?
>将闭包转换为i64值以将其传递给该回调的正确方法是什么?
我正在使用Rust的稳定版本.