如何在 JS 文件中使用导出的结构?

How to use exported struct in JS file?

我在 Rust 代码中有以下定义:

#[wasm_bindgen]
pub struct Point {
    x: i32,
    y: i32,
}

#[wasm_bindgen]
impl Point {
    #[wasm_bindgen(constructor)]
    pub fn new(x: i32, y: i32) -> Point {
        Point { x, y }
    }
}

我在 JS 文件中记录了创建的对象:

let p = new Point(23, 34);
console.log(p);

但是它用原型给了我一个指针值,我不知道怎么用。

如何用原型得到一个像{x: 23, y: 34 }这样的JS对象?

默认情况下,wasm_bindgen 在将它们传递给 JS 时不包含结构的实际字段,而是生成一个包装对象,该对象仅具有指向 (WASM) 堆上数据的指针并公开methods/properties 使用原型。您应该能够使用标准 JS 语法访问 (public) 个字段并调用方法,如 here in the wasm-bindgen reference.

所示

如果你真的想传回实际内容,你可以使用JsValue::from_serde, which allows serializing any type that implements Serialize into a JS object. Note that this object will not expose the methods, however - it's intended for passing plain data across the JS/WASM boundary. This is documented here in the wasm-bindgen reference