微信小程序调用 WebAssembly 烹饪指南

发布于:2025-02-11 ⋅ 阅读:(45) ⋅ 点赞:(0)

我们都是在夜里崩溃过的俗人,所幸终会天亮。明天就是新的开始,我们会变得与昨天不同。

一、Rust 导出 wasm

参考 wasm-bindgen 官方指南 https://wasm.rust-lang.net.cn/wasm-bindgen/introduction.html

wasm-bindgen,这是一个 Rust 库和 CLI 工具,它可以促进 wasm 模块和 JavaScript 之间的高级交互。

1、创建一个 wasm 项目

# 使用模板生成
# cargo generate --git https://gitee.com/tgodfather/wasm-pack-template
cargo generate --git https://github.com/rustwasm/wasm-pack-template

2、添加 js-sys 依赖

cargo add js-sys 

3、修改 lib.rs

定义三个外部函数,它们分别对应于 JavaScript 中的 console.logconsole.error 和 wx.showModal。通过使用 wasm_bindgen,这些函数可以在 Rust 代码中被调用,从而实现与 JavaScript 的交互。

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);

    #[wasm_bindgen(js_namespace = console)]
    fn error(s: &str);

    #[wasm_bindgen(js_namespace = wx)]
    fn showModal(param: &Object);
}

使用 rust 分别调用这三个函数,导出为 wasm 函数,

#[wasm_bindgen]
pub fn rs_log() {
    log("log");
}

#[wasm_bindgen]
pub fn rs_error() {
    log("error");
}

#[wasm_bindgen]
pub fn rs_show_modal() {
    // 创建一个 JavaScript 对象
    let options = Object::new();

    // 设置对象的属性
    Reflect::set(
        &options,
        &JsValue::from_str("title"),
        &JsValue::from_str("提示"),
    )
    .unwrap();
    Reflect::set(
        &options,
        &JsValue::from_str("content"),
        &JsValue::from_str("这是一个模态弹窗"),
    )
    .unwrap();

    // 创建回调函数
    let success_callback = Closure::wrap(Box::new(|res: JsValue| {
        let confirm = Reflect::get(&res, &JsValue::from_str("confirm"))
            .unwrap()
            .as_bool()
            .unwrap_or(false);
        let cancel = Reflect::get(&res, &JsValue::from_str("ca

网站公告

今日签到

点亮在社区的每一天
去签到