I'm new to Rust and WASM and struggling to get a first program running.
[dependencies]
wasm-bindgen = { version = "0.2.63" }
I have the following Rust that compiles to WASM
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
// let val = ["Hello", name].join(" ");
let val = format!("Hello {}", name);
return val;
}
And my node code (inspired by https://nodejs.dev/learn/nodejs-with-webassembly),
const fs = require("fs");
const wasmBuffer = fs.readFileSync("../pkg/hello_world_bg.wasm");
WebAssembly.instantiate(wasmBuffer)
.then((wasmModule) => {
// Exported function live under instance.exports
const greet = wasmModule.instance.exports.greet;
console.log(typeof greet);
const greeting = greet("Simon");
console.log("x", greeting);
})
.catch((err) => console.log(err));
This logs
function
x undefined
I tried two ways of concatenating the strings, or perhaps I am doing something wrong with the return value?
wasm_bindgenwould generally take care of the necessary glue to return aStringfrom a function in Rust. rustwasm.github.io/wasm-bindgen/reference/types/string.htmlmod utils;) while ensuring that it is complete and enables other people to reproduce the problem.greetonly needs to beformat!("Hello {}", name).mod utilswas put there bycargo generate --git https://github.com/rustwasm/wasm-pack-template- I have removed that import s it does not seem to be essentialwasm-pack build --target nodejsI was able to use the js file produced to call greet. That was simple for me, even though the js file I'm importing is impossible to follow at present