如何使用 WebAssembly 构造函数定义 Rust 结构?
How do I define a Rust struct with a WebAssembly constructor?
我正在尝试将结构从 Rust 导出到 WebAssembly,但出现以下错误:
Uncaught (in promise) TypeError: wasm.Test is not a constructor
生锈:
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()
解决后,returns 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,但出现以下错误:
Uncaught (in promise) TypeError: wasm.Test is not a constructor
生锈:
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()
解决后,returns 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();