Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to export a struct from Rust to WebAssembly, but I'm getting the following error:

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();

What would be the correct way to export a struct?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
246 views
Welcome To Ask or Share your Answers For Others

1 Answer

Note that init() when resolved, returns the WASM module's exports. So you won't find Test, instead you'd find test_new representing Test::new. This should be visible in the console after executing console.log(wasm);.

To resolve your issue, you instead need to import Test, where you initially import 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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...