Home > Mobile >  How do I return a string from a Rust function in Nodejs-WebAssembly using wasm bindgen?
How do I return a string from a Rust function in Nodejs-WebAssembly using wasm bindgen?

Time:11-24

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?

CodePudding user response:

When using WebInstantiate in node without more boilerplate, just like you did, I got the same result (undefined). What works seamlessly in the browser doesn't work so well in node.

But I got string exchange working when specifically building a node module with

wasm-pack build --target nodejs

With a node module, usage is also much simpler:

const wasmModule = require("./pkg/hello_world.js");
const greet = wasmModule.greet;
const greeting = greet("Simon");
console.log('greeting:', greeting);
  • Related