这是一个很好的问题,而且也有一些细微差别!在wasm-bindgen 指南(以及section about passing closures to JavaScript)中调用closures example 也是值得的,如果有必要也可以回馈给它!
不过,为了让您开始,您可以执行以下操作:
use wasm_bindgen::{Closure, JsValue};
#[wasm_bindgen]
pub fn start_game(
start_time: f64,
screen_width: f32,
screen_height: f32,
on_render: &js_sys::Function,
on_collision: &js_sys::Function,
) -> JsValue {
let cb = Closure::wrap(Box::new(move |time| {
time * 4.2
}) as Box<FnMut(f64) -> f64>);
// Extract the `JsValue` from this `Closure`, the handle
// on a JS function representing the closure
let ret = cb.as_ref().clone();
// Once `cb` is dropped it'll "neuter" the closure and
// cause invocations to throw a JS exception. Memory
// management here will come later, so just leak it
// for now.
cb.forget();
return ret;
}
返回值上方只是一个普通的 JS 对象(这里是 JsValue),我们使用您已经看到的 Closure 类型创建它。这将允许您快速将闭包返回给 JS,并且您也可以从 JS 调用它。
您还询问过存储可变对象等问题,这些都可以通过普通的 Rust 闭包、捕获等来完成。例如上面 FnMut(f64) -> f64 的声明是 JS 函数的签名,可以如果您真的想要,可以是任何类型的集合,例如 FnMut(String, MyCustomWasmBindgenType, f64) ->
Vec<u8>。要捕获本地对象,您可以这样做:
let mut camera = Camera::new();
let mut state = State::new();
let cb = Closure::wrap(Box::new(move |arg1, arg2| { // note the `move`
if arg1 {
camera.update(&arg2);
} else {
state.update(&arg2);
}
}) as Box<_>);
(或类似的东西)
这里camera 和state 变量将由闭包拥有并同时删除。更多关于闭包的信息can be found in the Rust book。
这里还值得简要介绍一下内存管理方面。在里面
上面的示例我们调用forget(),它会泄漏内存,如果多次调用 Rust 函数(因为它会泄漏大量内存),这可能是一个问题。这里的根本问题是在创建的 JS 函数对象引用的 WASM 堆上分配了内存。理论上,每当 JS 函数对象被 GC 时,都需要释放分配的内存,但我们无法知道何时发生(直到 WeakRef exists!)。
与此同时,我们选择了另一种策略。相关的记忆是
每当Closure 类型本身被删除时,就会被释放,提供
确定性破坏。然而,这使得使用起来很困难,因为我们需要手动确定何时删除Closure。如果forget 不适用于您的用例,删除Closure 的一些想法是:
首先,如果是只调用一次的JS闭包,那么可以使用Rc/RefCell
将Closure 放入封闭件本身(使用一些内部
可变性恶作剧)。我们也应该eventually
provide原生支持
FnOnce 也适用于 wasm-bindgen!
接下来,你可以返回一个辅助 JS 对象给 Rust,它有一个手册 free
方法。例如#[wasm_bindgen]-annotated 包装器。这个包装器会
然后需要在合适的时候在JS中手动释放。
如果可以的话,forget 是迄今为止最容易做到的事情
现在,但这绝对是一个痛点!我们等不及WeakRef 存在了:)