Last active
September 14, 2020 09:28
-
-
Save kuc-arc-f/88a33c67387eb55778a16fd86316436b to your computer and use it in GitHub Desktop.
Rust Serdeの、Serialize / Deserialize でjavascript変数を渡し、戻り値を取得
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [dependencies] | |
// wasm-bindgen = { version = "0.2", features = ["serde-serialize"] } | |
// serde = { version = "1.0", features = ["derive"] } | |
use serde::{Deserialize, Serialize}; | |
use std::collections::HashMap; | |
#[derive(Serialize, Deserialize)] | |
pub struct Example { | |
pub field1: HashMap<u32, String>, | |
pub field2: Vec<Vec<f32>>, | |
pub field3: [f32; 4], | |
pub field4: String, | |
} | |
#[wasm_bindgen] | |
pub fn send_example_to_js() -> JsValue { | |
let mut field1 = HashMap::new(); | |
field1.insert(0, String::from("ex")); | |
let example = Example { | |
field1, | |
field2: vec![vec![1., 2.], vec![3., 4.]], | |
field3: [1., 2., 3., 4.], | |
field4: "f4".to_string() | |
}; | |
JsValue::from_serde(&example).unwrap() | |
} | |
#[wasm_bindgen] | |
pub fn receive_example_from_js(val: &JsValue, f4_val: &str) -> JsValue { | |
let mut example: Example = val.into_serde().unwrap(); | |
example.field4 = String::from( f4_val) ; | |
console::log_1(&JsValue::from_str( &example.field4 )); | |
JsValue::from_serde(&example).unwrap() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// JS | |
let d = wasm.send_example_to_js(); | |
console.log( d ) | |
let d2 = wasm.receive_example_from_js(d, "f4-from-js") | |
console.log( d2 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment