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

前端 未结 3 1857
慢半拍i
慢半拍i 2020-11-27 19:24

I created a small Wasm file from this Rust code:

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

It builds

3条回答
  •  盖世英雄少女心
    2020-11-27 20:05

    You cannot directly return a Rust String or an &str. Instead allocate and return a raw byte pointer containing the data which has to be then encoded as a JS string on the JavaScript side.

    You can take a look at the SHA1 example here.

    The functions of interest are in

    • demos/bundle.js - copyCStr
    • demos/sha1/sha1-digest.rs - digest

    For more examples: https://www.hellorust.com/demos/sha1/index.html

提交回复
热议问题