- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 Rust 中使用 WinAPI,有些函数(如 EnumWindows()
)需要回调。回调通常接受一个额外的参数(类型 LPARAM
是 i64
的别名),您可以使用它来将一些自定义数据传递给回调。
我已经发送了Vec<T>
对象作为 WinAPI 回调的 LPARAM,它工作正常。例如“解包”lparam
Vec<RECT>
的值在我的例子中看起来像这样:
unsafe extern "system" fn enumerate_callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
let rects = lparam as *mut Vec<RECT>;
}
我现在必须传递闭包,而不是传递向量。我不能使用函数指针,因为我的闭包必须捕获一些变量,如果我使用函数,这些变量将无法访问。在 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);
// ...
}
中南合作:
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);
}
( Playground )
我收到这些错误:
error[E0277]: expected a `std::ops::FnMut<(i32,)>` 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<(i32,)>` closure, found `std::ffi::c_void`
|
= help: the trait `std::ops::FnMut<(i32,)>` 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<(i32,)>` 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<(i32,)>` closure, found `std::ffi::c_void`
|
= help: the trait `std::ops::FnMut<(i32,)>` is not implemented for `std::ffi::c_void`
= note: required for the cast to the object type `dyn std::ops::FnMut(i32) -> bool`
我想知道:
i64
的正确方法是什么?将其传递给该回调的值(value)?我使用的是稳定版的 Rust。
最佳答案
首先,代码有一些逻辑错误:
在许多平台(如 64 位)上将指针转换为 i32
是不正确的。指针可以使用所有这些位。截断指针然后在截断的地址调用函数将导致真正糟糕的事情。通常您希望使用机器大小的整数(usize
或 isize
)。
sum
值需要可变。
问题的实质是闭包是具体类型,占用的大小对于程序员来说是未知的,但对于编译器来说是已知的。 C 函数仅限于采用机器大小的整数。
因为闭包实现了 Fn*
特征之一,我们可以引用闭包对该特征的实现来生成一个特征对象。引用一个特征会导致一个胖指针,它包含两个指针大小的值。在这种情况下,它包含一个指向封闭数据的指针和一个指向 vtable 的指针,即实现特征的具体方法。
一般来说,对 dynamically-sized type type 的任何引用或 Box
将生成一个胖指针。
在 64 位机器上,胖指针总共有 128 位,将其转换为机器大小的指针会再次截断数据,导致真正糟糕的事情发生。
与计算机科学中的其他一切一样,解决方案是添加更多抽象层:
use std::os::raw::c_void;
fn enum_wnd_proc(some_value: i32, lparam: usize) {
let trait_obj_ref: &mut &mut FnMut(i32) -> bool = unsafe {
let closure_pointer_pointer = lparam as *mut c_void;
&mut *(closure_pointer_pointer as *mut _)
};
println!(
"predicate() executed and returned: {}",
trait_obj_ref(some_value)
);
}
fn main() {
let mut sum = 0;
let mut closure = |some_value: i32| -> bool {
println!("I'm summing {} + {}", sum, some_value);
sum += some_value;
sum >= 100
};
let mut trait_obj: &mut FnMut(i32) -> bool = &mut closure;
let trait_obj_ref = &mut trait_obj;
let closure_pointer_pointer = trait_obj_ref as *mut _ as *mut c_void;
let lparam = closure_pointer_pointer as usize;
enum_wnd_proc(20, lparam);
}
我们对胖指针进行第二次引用,这会创建一个瘦指针。这个指针只有一个机器整数大小。
也许图表会有所帮助(或有害)?
Reference -> Trait object -> Concrete closure
8 bytes 16 bytes ?? bytes
因为我们使用的是原始指针,所以现在程序员有责任确保闭包在使用它的地方仍然存在!如果 enum_wnd_proc
将指针存储在某处,您必须非常小心不要在关闭闭包后使用它。
作为旁注,在转换特征对象时使用 mem::transmute
:
use std::mem;
let closure_pointer_pointer: *mut c_void = unsafe { mem::transmute(trait_obj) };
产生更好的错误信息:
error[E0512]: transmute called with types of different sizes
--> src/main.rs:26:57
|
26 | let closure_pointer_pointer: *mut c_void = unsafe { mem::transmute(trait_obj) };
| ^^^^^^^^^^^^^^
|
= note: source type: &mut dyn std::ops::FnMut(i32) -> bool (128 bits)
= note: target type: *mut std::ffi::c_void (64 bits)
另见
关于rust - 如何通过原始指针将闭包作为参数传递给 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38995701/
我刚接触 C 语言几周,所以对它还很陌生。 我见过这样的事情 * (variable-name) = -* (variable-name) 在讲义中,但它到底会做什么?它会否定所指向的值吗? 最佳答案
我有一个指向内存地址的void 指针。然后,我做 int 指针 = void 指针 float 指针 = void 指针 然后,取消引用它们以获取值。 { int x = 25; vo
我正在与计算机控制的泵进行一些串行端口通信,我用来通信的 createfile 函数需要将 com 端口名称解析为 wchar_t 指针。 我也在使用 QT 创建一个表单并获取 com 端口名称作为
#include "stdio.h" #include "malloc.h" int main() { char*x=(char*)malloc(1024); *(x+2)=3; --
#include #include main() { int an_int; void *void_pointer = &an_int; double *double_ptr = void
对于每个时间步长,我都有一个二维矩阵 a[ix][iz],ix 从 0 到 nx-1 和 iz 从 0 到 nz-1。 为了组装所有时间步长的矩阵,我定义了一个长度为 nx*nz*nt 的 3D 指针
我有一个函数,它接受一个指向 char ** 的指针并用字符串填充它(我猜是一个字符串数组)。 *list_of_strings* 在函数内部分配内存。 char * *list_of_strings
我试图了解当涉及到字符和字符串时,内存分配是如何工作的。 我知道声明的数组的名称就像指向数组第一个元素的指针,但该数组将驻留在内存的堆栈中。 另一方面,当我们想要使用内存堆时,我们使用 malloc,
我有一个 C 语言的 .DLL 文件。该 DLL 中所有函数所需的主要结构具有以下形式。 typedef struct { char *snsAccessID; char *
我得到了以下数组: let arr = [ { children: [ { children: [], current: tru
#include int main(void) { int i; int *ptr = (int *) malloc(5 * sizeof(int)); for (i=0;
我正在编写一个程序,它接受一个三位数整数并将其分成两个整数。 224 将变为 220 和 4。 114 将变为 110 和 4。 基本上,您可以使用模数来完成。我写了我认为应该工作的东西,编译器一直说
好吧,我对 C++ 很陌生,我确定这个问题已经在某个地方得到了回答,而且也很简单,但我似乎找不到答案.... 我有一个自定义数组类,我将其用作练习来尝试了解其工作原理,其定义如下: 标题: class
1) this 指针与其他指针有何不同?据我了解,指针指向堆中的内存。如果有指向它们的指针,这是否意味着对象总是在堆中构造? 2)我们可以在 move 构造函数或 move 赋值中窃取this指针吗?
这个问题在这里已经有了答案: 关闭 11 年前。 Possible Duplicate: C : pointer to struct in the struct definition 在我的初学者类
我有两个指向指针的结构指针 typedef struct Square { ... ... }Square; Square **s1; //Representing 2D array of say,
变量在内存中是如何定位的?我有这个代码 int w=1; int x=1; int y=1; int z=1; int main(int argc, char** argv) { printf
#include #include main() { char *q[]={"black","white","red"}; printf("%s",*q+3); getch()
我在“C”类中有以下函数 class C { template void Func1(int x); template void Func2(int x); }; template void
我在64位linux下使用c++,编译器(g++)也是64位的。当我打印某个变量的地址时,例如一个整数,它应该打印一个 64 位整数,但实际上它打印了一个 48 位整数。 int i; cout <<
我是一名优秀的程序员,十分优秀!