如何通过wasm-bindgen将对象数组传递给WebAssembly并将其转换为结构向量?

时间:2018-10-13 18:52:19

标签: rust webassembly serde wasm-bindgen

可以传递这样的整数数组:

const js = import("./webassembly_rust");
let array_nums = [1,2,3,4,5,6,7,8,9];

js.then(js => {
  js.test( array_nums );
}); 

到WebAssembly并将其保存在这样的向量中:

extern crate serde_json;
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[macro_use]
extern crate serde_derive;

#[wasm_bindgen]
pub fn test(array: JsValue) {
    let elements: Vec<u32> = array.into_serde().unwrap();
}

也可以像这样传递单个对象:

const js = import("./webassembly_rust");
let jsObject = {name: "hello world", id: "99", parent_id: "11"};

js.then(js => {
  js.test( jsObject );
}); 

到WebAssembly并将其保存为Element结构,如下所示:

extern crate serde_json;
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[macro_use]
extern crate serde_derive;

#[derive(Serialize, Deserialize)]
pub struct Element {
    name: String,
    id: String,
    parent_id: String,
}

#[wasm_bindgen]
pub fn test(js_object: &JsValue) {
    let element: Element = js_object.into_serde().unwrap();
}

接下来我要尝试的是传递这样的对象数组:

const js = import("./webassembly_rust");
let arrayOfObjects = [
  {name: "hello world", id: "99", parent_id: "88"},
  {name: "hello world2", id: "88", parent_id: "12"},
  {name: "hello world3", id: "77", parent_id: "88"}
]

js.then(js => {
  js.test( arrayOfObjects );
}); 

到WebAssembly,并将其保存为Element结构的向量,如下所示:

extern crate serde_json;
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[macro_use]
extern crate serde_derive;

#[derive(Serialize, Deserialize)]
pub struct Element {
    name: String,
    id: String,
    parent_id: String,
}

#[wasm_bindgen]
pub fn test(js_objects: &JsValue) {
    let elements: Vec<Element> = js_objects.into_serde().unwrap();
}

这可以编译,但是当我运行这段代码时,我得到了错误:

func $__rust_start_panic (param i32) (result i32)
  unreachable
  unreachable
end

screenshot_promise_rejection_error

传递一个由数字组成的对象数组,如下所示:

const js = import("./webassembly_rust");
let arrayOfNumObjects = [
    {name: 1, id: 2, parent_id: 3 },
    {name: 1, id: 2, parent_id: 3 },
    {name: 1, id: 2, parent_id: 3 }
]

js.then(js => {
  js.test( arrayOfNumObjects );
}); 
Element结构仅包含u32值时,可以

使用WebAssembly。

extern crate serde_json;
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[macro_use]
extern crate serde_derive;

#[derive(Serialize, Deserialize)]
pub struct Element {
    name: u32,
    id: u32,
    parent_id: u32,
}

#[wasm_bindgen]
pub fn test(js_objects: &JsValue) {
    let elements: Vec<Element> = js_objects.into_serde().unwrap();
}

问题似乎是由String结构中的Element类型引起的。

我做错了什么?

我找到了以下文章,但在其中找不到解决问题的方法:

1 个答案:

答案 0 :(得分:4)

按照说明获取basic Rust / WASM setup,然后添加对arbitrary data via Serde的支持。

我已更改您的代码以返回一个数字并打印出该数字,只是为了查看它是否正常工作。

Cargo.toml

[package]
name = "ww"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
edition = "2018"

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
serde_json = "1.0.32"
serde_derive = "1.0.80"
serde = "1.0.80"

src / lib.rs

extern crate serde_json;
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[macro_use]
extern crate serde_derive;

#[derive(Serialize, Deserialize)]
pub struct Element {
    name: String,
    id: String,
    parent_id: String,
}

#[wasm_bindgen]
pub fn test(js_objects: &JsValue) -> i32 {
    let elements: Vec<Element> = js_objects.into_serde().unwrap();
    elements
        .iter()
        .map(|e| {
            let id = e.id.parse::<i32>().unwrap_or(0);
            let parent_id = e.parent_id.parse::<i32>().unwrap_or(0);
            id + parent_id
        })
        .sum()
}

index.js

const js = import("./ww");

let arrayOfObjects = [
  { name: "hello world", id: "99", parent_id: "88" },
  { name: "hello world2", id: "88", parent_id: "12" },
  { name: "hello world3", id: "77", parent_id: "88" },
]

js.then(js => {
  const sum = js.test(arrayOfObjects);
  console.log(sum);
});

package.json

{
  "scripts": {
    "serve": "webpack-dev-server"
  },
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.0.1",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.1.0"
  }
}

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: "./index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index.js",
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "Getting started with WASM"
    })
  ],
  mode: "development"
};

然后运行:

# once
npm install
# every time the code changes
cargo +nightly build --target wasm32-unknown-unknown
wasm-bindgen target/wasm32-unknown-unknown/debug/*.wasm --out-dir .
npm run serve

在支持WASM的浏览器中访问页面。


细心的读者会注意到,我所做的与OP没什么不同。这是因为此代码已经按原样工作。每次更改Rust代码时,请确保:

  1. 构建您的Rust代码
  2. 重新运行wasm-bindgen