Search code examples
angularrustwebassemblywasm-bindgen

return a rust-wasm vector in angular application


I have a basic angular app and a Rust wasm pack, and I want to call functions in the Rust compiled code in angular. The rust code template is taken from the rust-pack-template-repo in lib.rs is the following:

mod utils;
use wasm_bindgen::prelude::*;


#[wasm_bindgen]
pub fn add_one(number: u32) -> u32
{
   number + 1
}

#[wasm_bindgen]
pub fn test_vec_output(num_samples: u32) -> Vec<u32>
{
  let my_vec: Vec<u32> = vec![12; num_samples as usize];

  my_vec
}

In the Angular app side, I used the following code sample to call the rust-wasm function:

async testRustWasmFunctions()
{
import('../wasm-test-pack/pkg/myDummyPackage_bg.wasm').then((response) => {
      this.myFirstResult = response.add_one(1);
      console.log("Test dummy add: " + this.myFirstResult); // Works fine !! returns 2
      console.log("Test dummy vector: " + response.test_vec_output(1,1)); // Only works if I take two arguments
    });
}

In the HTML part the function is called like this:

<button (click)="testRustWasmFunctions()"><\button>

The response.test_vec_output(1,1)) function call returns no error (in angular) when called with two arguments, and the console result returns undefined. While the function add_one works just fine and returns the correct result.

Is there a better way to import rust-wasm pack to angular than this, such that it is easy to process vectors?


Solution

  • wasm-bindgen generates a js file (should be called myDummyPackage.js) which is responsible for setting up a bunch of stuff (like heap and wrappers).

    You can try to import generated .js file, if it doesn't work I recommend looking at these tutorials:

    • This tutorial to get an ES module (you should use wasm-pack --target web for this)
    • This tutorial to setup webpack