如何在WebAssembly中从Rust返回一个字符串(或类似的)?

qvk1mo1f  于 11个月前  发布在  其他
关注(0)|答案(4)|浏览(102)

我从这个Rust代码创建了一个小的Wasm文件:

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

字符串
它可以构建,并且可以从JS调用hello函数:

<!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>


我的问题是alert显示“undefined”。如果我返回一个i32,它会工作并显示i32。我也试图返回一个String,但它不工作(它仍然显示“undefined”)。
有没有办法在WebAssembly中从Rust返回一个字符串?我应该使用什么类型?

at0kjp5o

at0kjp5o1#

WebAssembly只支持一些数字类型,这是所有可以通过导出函数返回的类型。
当你编译到WebAssembly时,你的字符串将保存在模块的线性内存中。为了从宿主JavaScript中读取这个字符串,你需要返回一个对它在内存中的位置的引用,以及字符串的长度,即两个整数。这允许你从内存中读取字符串。
无论您使用哪种语言编译WebAssembly,都可以使用相同的技术。How can I return a JavaScript string from a WebAssembly function提供了该问题的详细背景。
对于Rust,你需要使用外部函数接口(FFI),使用CString类型,如下所示:

use std::ffi::CString;
use std::os::raw::c_char;

static HELLO: &'static str = "hello from rust";

#[no_mangle]
pub fn get_hello() -> *mut c_char {
    let s = CString::new(HELLO).unwrap();
    s.into_raw()
}

#[no_mangle]
pub fn get_hello_len() -> usize {
    HELLO.len()
}

字符串
上面的代码导出了两个函数,get_hello返回字符串的引用,get_hello_len返回字符串的长度。
将上述代码编译为wasm模块后,可以按如下方式访问字符串:

const res = await fetch('chip8.wasm');
const buffer = await res.arrayBuffer();
const module = await WebAssembly.compile(buffer);
const instance = await WebAssembly.instantiate(module);

// obtain the module memory
const linearMemory = instance.exports.memory;

// create a buffer starting at the reference to the exported string
const offset = instance.exports.get_hello();
const stringBuffer = new Uint8Array(linearMemory.buffer, offset,
  instance.exports.get_hello_len());

// create a string from this buffer
let str = '';
for (let i=0; i<stringBuffer.length; i++) {
  str += String.fromCharCode(stringBuffer[i]);
}

console.log(str);


C等价物can be seen in action in a WasmFiddle

qmelpv7a

qmelpv7a2#

从Rust fn返回字符串到ReactApp
TLDR:

添加到main.rs use wasm_bindgen::prelude::*;
使用JsValue作为fn的返回类型。
从fn JSValue::from_str("string")返回

为函数创建Rust库

mkdir ~/hello-from-rust-demo \
cd ~/hello-from-rust-demo \
cargo new --lib hello-wasm \
cd 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

创建React App演示Rust函数

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;

启动应用

yarn start


Hello from rust, Human!

mbzjlibv

mbzjlibv3#

不能直接返回Rust String&str。而是分配并返回一个原始字节指针,其中包含数据,然后必须在JavaScript端编码为JS字符串。
你可以看看SHA1的例子here
感兴趣的功能是

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

更多示例:https://www.hellorust.com/demos/sha1/index.html

biswetbf

biswetbf4#

我看到的大多数例子都复制了两次字符串。首先在WASM端,复制到CString中,或者将Vec缩小到它的容量,然后在JS端解码UTF-8。
考虑到我们经常为了速度而使用WASM,我试图实现一个重用Rust向量的版本。

use std::collections::HashMap;

/// Byte vectors shared with JavaScript.
///
/// A map from payload's memory location to `Vec<u8>`.
///
/// In order to deallocate memory in Rust we need not just the memory location but also it's size.
/// In case of strings and vectors the freed size is capacity.
/// Keeping the vector around allows us not to change it's capacity.
///
/// Not thread-safe (assuming that we're running WASM from the single JavaScript thread).
static mut SHARED_VECS: Option<HashMap<u32, Vec<u8>>> = None;

extern "C" {
    fn console_log(rs: *const u8);
    fn console_log_8859_1(rs: *const u8);
}

#[no_mangle]
pub fn init() {
    unsafe { SHARED_VECS = Some(HashMap::new()) }
}

#[no_mangle]
pub fn vec_len(payload: *const u8) -> u32 {
    unsafe {
        SHARED_VECS
            .as_ref()
            .unwrap()
            .get(&(payload as u32))
            .unwrap()
            .len() as u32
    }
}

pub fn vec2js<V: Into<Vec<u8>>>(v: V) -> *const u8 {
    let v = v.into();
    let payload = v.as_ptr();
    unsafe {
        SHARED_VECS.as_mut().unwrap().insert(payload as u32, v);
    }
    payload
}

#[no_mangle]
pub extern "C" fn free_vec(payload: *const u8) {
    unsafe {
        SHARED_VECS.as_mut().unwrap().remove(&(payload as u32));
    }
}

#[no_mangle]
pub fn start() {
    unsafe {
        console_log(vec2js(format!("Hello again!")));
        console_log_8859_1(vec2js(b"ASCII string." as &[u8]));
    }
}

字符串
JavaScript部分:

(function (iif) {

  function rs2js (mod, rs, utfLabel = 'utf-8') {
    const view = new Uint8Array (mod.memory.buffer, rs, mod.vec_len (rs))
    const utf8dec = new TextDecoder (utfLabel)
    const utf8 = utf8dec.decode (view)
    mod.free_vec (rs)
    return utf8}

  function loadWasm (cache) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming
    WebAssembly.instantiateStreaming (fetch ('main.wasm', {cache: cache ? "default" : "no-cache"}), {env: {
      console_log: function (rs) {if (window.console) console.log ('main]', rs2js (iif.main, rs))},
      console_log_8859_1: function (rs) {if (window.console) console.log ('main]', rs2js (iif.main, rs, 'iso-8859-1'))}
    }}) .then (results => {
      const exports = results.instance.exports
      exports.init()
      iif.main = exports
      iif.main.start()})}

  // Hot code reloading.
  if (window.location.hostname == '127.0.0.1' && window.location.port == '43080') {
    window.setInterval (
      function() {
        // Check if the WASM was updated.
        fetch ('main.wasm.lm', {cache: "no-cache"}) .then (r => r.text()) .then (lm => {
          lm = lm.trim()
          if (/^\d+$/.test (lm) && lm != iif.lm) {
            iif.lm = lm
            loadWasm (false)}})},
      200)
  } else loadWasm (true)

} (window.iif = window.iif || {}))


这里的代价是,我们在WASM中使用HashMap,这可能会增加大小,除非已经需要HashMap
一个有趣的替代方案是使用tables与JavaScript共享(payload,length,capacity)三元组,并在释放字符串时将其取回。
P.S.有时候我们并不想一开始就分配Vec
在这种情况下,我们可以将内存跟踪移动到JavaScript:

extern "C" {
    fn new_js_string(utf8: *const u8, len: i32) -> i32;
    fn console_log(js: i32);
}

fn rs2js(rs: &str) -> i32 {
    assert!(rs.len() < i32::max_value() as usize);
    unsafe { new_js_string(rs.as_ptr(), rs.len() as i32) }
}

#[no_mangle]
pub fn start() {
    unsafe {
        console_log(rs2js("Hello again!"));
    }
}
(function (iif) {
  function loadWasm (cache) {
    WebAssembly.instantiateStreaming (fetch ('main.wasm', {cache: cache ? "default" : "no-cache"}), {env: {
      new_js_string: function (utf8, len) {
        const view = new Uint8Array (iif.main.memory.buffer, utf8, len)
        const utf8dec = new TextDecoder ('utf-8')
        const decoded = utf8dec.decode (view)
        let stringId = iif.lastStringId
        while (typeof iif.strings[stringId] !== 'undefined') stringId += 1
        if (stringId > 2147483647) {  // Can't easily pass more than that through WASM.
          stringId = -2147483648
          while (typeof iif.strings[stringId] !== 'undefined') stringId += 1
          if (stringId > 2147483647) throw new Error ('Out of string IDs!')}
        iif.strings[stringId] = decoded
        return iif.lastStringId = stringId},
      console_log: function (js) {
        if (window.console) console.log ('main]', iif.strings[js])
        delete iif.strings[js]}
    }}) .then (results => {
      iif.main = results.instance.exports
      iif.main.start()})}

  loadWasm (true)
} (window.iif = window.iif || {strings: {}, lastStringId: 1}))

的字符串

相关问题