0

I tried to compile this Rust code into WebAssembly:

#[no_mangle]
pub fn rust_function() -> String {
    let mut a = vec![];
    for x in 0..100 {
        a.push(x);
    }
    return a.iter()
        .map(|x| format!("{}", x))
        .collect::<Vec<_>>()
        .join("-");
}

When I execute it with WebAssembly in NodeJS, it gives an undefined result:

const fs = require('fs');
const buf = fs.readFileSync('target/wasm32-unknown-unknown/release/hello_world.wasm');
function toUint8Array(buf) {
  var u = new Uint8Array(buf.length)
  for (var i = 0; i < buf.length; ++i) {
    u[i] = buf[i]
  }
  return u
}

const arrayBuffer = toUint8Array(buf);
const result = WebAssembly.instantiate(arrayBuffer);

result.then((res)=>{
  console.log(res.instance.exports.rust_function());
})

It works well for other targets.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Darktalker
  • 346
  • 2
  • 6
  • 2
    WebAssembly only knows four types: `i32`, `i64`, `f32` and `f64`. You are passing a `String`, so that is of course not going to work. I suggest you check out [this example](https://www.hellorust.com/demos/sha1/index.html) of returning a String through pointers – aochagavia Dec 13 '17 at 14:13
  • You're returning a type which is not 'native' to WebAssembly. For how to return a string from Rust, see this question: https://stackoverflow.com/questions/47529643/how-to-return-a-string-or-similar-from-rust-in-webassembly – ColinE Dec 13 '17 at 14:18
  • Just saying: your function can be written: `(0..10).map(|x| x.to_string()).collect::>().join("-")` – Boiethios Dec 13 '17 at 14:55

0 Answers0