我正在尝试将结构从 Rust 导出到 WebAssembly,但出现以下错误:
Uncaught (in promise) TypeError: wasm.Test is not a constructor
rust :
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen]
pub struct Test {
pub x: i32,
}
#[wasm_bindgen]
impl Test {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self {
x: 0,
}
}
}
JS:import init from './wasm.js'
async function run() {
const wasm = await init().catch(console.error);
console.log(wasm);
let test = new wasm.Test();
console.log(test);
}
run();
导出结构的正确方法是什么?
最佳答案
请注意 init()
解析后,返回 WASM 模块的导出。所以你不会找到 Test
,而是找到 test_new
代表Test::new
.执行 console.log(wasm);
后,这应该在控制台中可见.
要解决您的问题,您需要导入 Test
,您最初在此处导入 init
.
import init, { Test } from './wasm.js';
async function run() {
const wasm = await init().catch(console.error);
console.log(wasm);
let test = new Test();
console.log(test);
}
run();
关于rust - 如何使用 WebAssembly 构造函数定义 Rust 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65669001/