我试图在wasm_bindgen中使用JS函数,该函数具有一个类似于fetch之类的对象参数:
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen]
fn fetch(resource: &str, config: &JsValue);
}(仅以fetch为例,我知道有更好的方法来使用从锈菌中提取.)
我不知道如何在铁锈中建模配置对象。
我试过使用JsValue,但JsValue似乎只能由原始类型而不是对象创建。
我在网上看到了一些建议,认为serde可以在这里有所帮助,但我找不到任何具体的例子,我试图让它自己发挥作用也没有结果。
提前感谢您对此进行调查!
发布于 2021-03-31 18:43:37
看起来,您可以使用js_sys::Reflect访问或设置任意值,也可以使用serde解析/取消解析值。
对于第一种方法,此资源解释如何在非类型化对象上读取或写入属性:https://rustwasm.github.io/docs/wasm-bindgen/reference/accessing-properties-of-untyped-js-values.html和使用此接口的示例可在web-sys本身中找到,后者定义了在为fetch():https://docs.rs/web-sys/0.3.50/src/web_sys/features/gen_RequestInit.rs.html#4构建配置对象时使用的RequestInit对象。
另一种方法是使用serde。这方面的例子可以在https://rustwasm.github.io/docs/wasm-bindgen/examples/fetch.html上找到,更详细的解释可以在https://rustwasm.github.io/docs/wasm-bindgen/reference/arbitrary-data-with-serde.html上找到。
在定义了要序列化和反序列化的对象之后,可以使用JsValue::from_serde()和.into_serde()进行JsValue的转换。
发布于 2021-04-01 10:14:36
同事指出的另一个选择是使用serde_wasm_bindgen,例如。
#[derive(Serialize, Deserialize)]
struct FetchConfig {
pub method: String,
}
fn call_fetch() {
let config = FetchConfig {
method: "post".to_string()
};
let config = serde_wasm_bindgen::to_value(&config).unwrap();
fetch("https://example.com", &config);
}https://stackoverflow.com/questions/66886242
复制相似问题