rust - 如何通过 WebAssembly 将 Rust 闭包返回给 JavaScript?

标签 rust webassembly wasm-bindgen

关于closure.rs的评论非常棒,但是我无法让它从 WebAssembly 库返回闭包。

我有这样一个函数:

#[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,
) -> ClosureTypeHere {
    // ...
}

在该函数中我做了一个闭包,假设 Closure::wrap 是拼图的一部分,并从 closure.rs 复制):

let cb = Closure::wrap(Box::new(move |time| time * 4.2) as Box<FnMut(f64) -> f64>);

如何从 start_game 返回这个回调,ClosureTypeHere 应该是什么?

想法是 start_game 将创建本地可变对象 - 如相机,JavaScript 端应该能够调用 Rust 返回的函数以更新该相机。

最佳答案

这是一个很好的问题,也有一些细微差别!值得调用 closures examplewasm-bindgen指南(和 section about passing closures to JavaScript ),如有必要,最好也对此做出贡献!

不过,为了让你开始,你可以做这样的事情:

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<_>);

(或类似的东西)

这里是 camerastate变量将由闭包拥有并同时被删除。关于闭包的更多信息 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 native 支持 对于 FnOncewasm-bindgen还有!

  • 接下来,您可以返回一个辅助 JS 对象给 Rust,它有一个手册 free 方法。例如 #[wasm_bindgen] -带注释的包装器。这个包装器会 然后需要在合适的时候在JS中手动释放。

如果可以的话,forget是迄今为止最简单的事情 现在,但这绝对是一个痛点!我们等不及了 WeakRef存在:)

关于rust - 如何通过 WebAssembly 将 Rust 闭包返回给 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53214434/

相关文章:

multithreading - 多个线程如何共享一个迭代器?

rust - 分配的匿名与结构生命周期

rust - 如何在WASM-Bindgen和Rust中实际获取响应正文的文本

rust - 如何确保将正确的 HTML 元素从 JavaScript 传递到我的 Rust 函数?

javascript - asm.js 和 WebAssembly 有什么区别?

rust - 使用 web_sys::HtmlButtonElement 失败

scala - 如何将 Scala 匿名特征实现转换为 Rust?

vector - RefCell中对数据的不变引用

authentication - Blazor WebAssembly SignalR 身份验证

emscripten - 在 emscripten 中禁用链接 libc