rust - 如何使用 WebAssembly 构造函数定义 Rust 结构?

标签 rust webassembly

我正在尝试将结构从 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/

相关文章:

generics - 如何为涉及对中间局部变量的引用的闭包指定生命周期边界?

rust - 为什么 Rust 要求宏名称末尾有感叹号?

rust - 在 wasm-bindgen 中扩展 AudioWorkletProcessor?

.net - 为什么我在浏览器 > 开发工具 > 网络中的 Blazor WebAssembly 应用程序上看不到 DLL 和 dotnet.wasm?

javascript - Chrome 扩展拒绝将字符串评估为 JavaScript,因为 emscripten 生成的文件中有 'unsafe-eval'

rust - 火箭 - 由于未实现特征,我的守卫内的使用状态失败

rust - 这个函数可以用 Rust 创建吗?

rust - 匹配模式中变量的生命周期

python - 在 BigQuery 中运行 python 函数

emscripten - 在 emscripten 中禁用链接 libc