How to return a string (or similar) from Rust in WebAssembly?

Viewed 10028

I created a small Wasm file from this Rust code:

#[no_mangle]
pub fn hello() -> &'static str {
    "hello from rust"
}

It builds and the hello function can be called from JS:

<!DOCTYPE html>
<html>
<body>
  <script>
    fetch('main.wasm')
    .then(response => response.arrayBuffer())
    .then(bytes => WebAssembly.instantiate(bytes, {}))
    .then(results => {
      alert(results.instance.exports.hello());
    });
  </script>
</body>
</html>

My problem is that the alert displays "undefined". If I return a i32, it works and displays the i32. I also tried to return a String but it does not work (it still displays "undefined").

Is there a way to return a string from Rust in WebAssembly? What type should I use?

4 Answers

Return String from Rust fn to ReactApp

TLDR:
Add to main.rs use wasm_bindgen::prelude::*;
Use JsValue as the return type of fn.
Return from fn JSValue::from_str("string")


Create Rust Library for Function

mkdir ~/hello-from-rust-demo \
cd ~/hello-from-rust-demo \
cargo new --lib hello-wasm \
cargo add wasm-bindgen \
code ~/hello-from-rust-demo/hello-wasm/src/lib.rs
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn hello(name: &str) -> JsValue {
    JsValue::from_str(&format!("Hello from rust, {}!", name))
}
cargo install wasm-pack \
wasm-pack build --target web

Create React App to Demo Rust Function

cd ~/hello-from-rust-demo \
yarn create react-app hello \
cd hello \
yarn add ../hello-wasm/pkg \
code ~/hello-from-rust-demo/hello/src/App.js

App.js

import init, { hello } from 'hello-wasm';
import { useState, useEffect } from 'react';

function App() {
  const [hello, setHello] = useState(null);
  useEffect(() => {
    init().then(() => {
      setHello(()=>hello);
    })
  }, []);

  return (
    hello("Human")
  );
}

export default App;

Start App

yarn start

Hello from rust, Human!

Related