97·跨平台进阶

wasm-bindgen 与 JS 互操作

wasm-bindgen 与 JS 互操作

学习目标

  1. 掌握 Rust 调用 JS
  2. 掌握 JS 调用 Rust
  3. 理解类型转换

核心概念

调用 JS 函数

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);

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

    #[wasm_bindgen(js_name = fetch)]
    async fn js_fetch(url: &str) -> JsValue;
}

#[wasm_bindgen]
pub fn demo() {
    alert("Hello!");
    log("console.log from Rust");
}

暴露给 JS

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Calculator {
    value: f64,
}

#[wasm_bindgen]
impl Calculator {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Calculator {
        Calculator { value: 0.0 }
    }

    pub fn add(&mut self, n: f64) -> f64 {
        self.value += n;
        self.value
    }

    pub fn get(&self) -> f64 {
        self.value
    }
}

错误处理

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn parse_number(s: &str) -> Result<f64, JsError> {
    s.parse::<f64>().map_err(|e| JsError::new(&e.to_string()))
}

回调

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn call_js_callback(callback: &js_sys::Function) {
    let this = JsValue::null();
    let arg = JsValue::from_str("hello from Rust");
    callback.call1(&this, &arg).unwrap();
}

小结

语法用途
#[wasm_bindgen]暴露给 JS
extern "C"调用 JS 函数
JsValue通用 JS 值
JsErrorJS 错误
js_sysJS 标准库
web_sysWeb API

练习编辑器

rust
Loading...