关于webassembly:如何在Wasm(Rust)中访问JS对象属性?

How to access JS object properties in Wasm (Rust)?

我正在使用wasm bindgen,并且具有以下功能:

1
2
3
4
#[wasm_bindgen]
pub fn obj(o: &JsValue){
console::log_1(o);
}

在js中,我将此函数称为obj({name:"john"});
它工作正常,但是当我尝试console::log_1(o.name);
它给出错误unknown field指向name


JsValue没有字段name。要获取此字段,您必须声明JS对象。

变体1

将Serde添加到您的依赖项中:

1
2
serde ="^1.0.101"
serde_derive ="^1.0.101"

锈迹代码:

1
2
3
4
5
6
7
8
9
10
11
12
extern crate serde;

#[derive(Serialize, Deserialize)]
pub struct User {
    pub name: String,
}

#[wasm_bindgen]
pub fn obj(o: &JsValue){
    let user: User = o.into_serde().unwrap();
    console::log_1(user.name);
}

Variant 2

另一种方法是直接使用wasm-bindgen,但我从未使用过。我认为它应该像这样工作:

1
2
3
4
5
6
7
8
9
#[wasm_bindgen]
pub struct User {
    pub name: String,
}

#[wasm_bindgen]
pub fn obj(o: User){
    console::log_1(o.name);
}