1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RustAdvent Calendar 2022

Day 23

Rustのwasm-bindgenで浮動小数点のCast評価

Posted at

wasm-bindgenを見ながらCastの練習

JS <-> Rust間の値の受け渡しを評価。
Float64ArrayでRustに渡してJSにFloat64Arrayで返す。

途中Rust内で、f64 -> vec -> ndarray matrix -> vec -> Box<[f64]> に変換

Curgo.toml
[dependencies]
wasm-bindgen = "0.2.63"
ndarray = "0.15.6"
index.js
let f64 = new Float64Array([1, 2, 3, 4, 5, 6, 7, 8, 9]);
let resf64 = wasm.take_boxed_number_slice_by_value(f64);
console.log(resf64);
console.log(resf64 instanceof Float64Array); // true
lib.rs

use wasm_bindgen::prelude::*;
use ndarray::prelude::*;

...


fn type_of<T>(_: T) -> String{
    let a = std::any::type_name::<T>();
    return a.to_string();
}

#[wasm_bindgen]
pub fn take_boxed_number_slice_by_value(x: &[f64]) -> Box<[f64]> {
   
    let mut vec = Vec::new();
    vec.extend(x.iter().copied());

    let matrix = Array::from_vec(vec).into_shape((3,3)).unwrap();
    alert(&format!("{:?}", matrix));

    let (w, h) = {
        let shape = matrix.shape();
        (shape[1], shape[0])
    };
    let v1 = matrix.into_shape(h*w).unwrap().to_vec().into_boxed_slice();
    v1
}

メモ

  • 公式のHello Worldを見ながらwasm-bindgen環境をセットアップすると、npm linkの記述がない為、変更の反映ができなくてハマるので注意する。npm linkこちらを参考にした。
  • extern createはいらない。Cargo.tomlに書いたら呼び出せる
  • JS<->Rustで Float64Arrayは古い記事ではpointerで渡しているが、書き方が改善している。
  • ローカルのPlayground環境はJupyterが使える
$ brew install jupyter
$ cargo install evcxr_jupyter
$ evcxr_jupyter --install
  • Jupyter上のRustでndarrayを使う場合はおまじないが必要
:dep showata = { version = "0.3", features=["show_ndarray"]}
:dep ndarray = "0.14"

use showata::Showable;
use ndarray::prelude::*;

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?