2

I have a rust program which I would like to run as web assembly in javascript. I have a function which I want to return a 3D array, so I can plot some data on a graph on the frontend, but I cannot find a way to return such data. Having a look at js_sys there is no general Array type, only specific types for 2D arrays such as Uint32Array.

I would like the function signature to look something like this:

#[wasm_bindgen]
pub fn sk_dataset(input: &str) -> Vec<Vec<i32>>;

I have tried return a struct with the wasm_bindgen decorator like this:

#[wasm_bindgen]
pub struct DataSet {

    pub data: Vec<Vec<i32>>
}

But I get an error stating that

the trait bound `Vec<i32>: JsObject` is not satisfied
required because of the requirements on the impl of `IntoWasmAbi` for `Box<[Vec<i32>]>`

The tutorial over at https://rustwasm.github.io/docs/wasm-bindgen/reference/types/exported-rust-types.html only has examples of structs exported with basic types like i32s, how can I export a struct with more complex members?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
m.tracey
  • 173
  • 1
  • 10
  • 2
    Looks like I neglected to read the page on Serde, which enables you to serialise arbitrary types: https://rustwasm.github.io/docs/wasm-bindgen/reference/arbitrary-data-with-serde.html – m.tracey May 22 '22 at 01:00
  • Just a word of warning, serialization and deserialization will be fairly slow, especially if the `Vec`s are large. I don't know enough about wasm bindgen to recommend a better solution though. – Aiden4 May 22 '22 at 04:04
  • your question sounds similar to that example of wasm where an menory buffer ist returned from Rust to JS. may be that approach is a better fit. https://rustwasm.github.io/docs/book/game-of-life/implementing.html – Reinhard Jul 25 '23 at 17:50

0 Answers0