Created
October 16, 2022 13:29
-
-
Save jsjolund/dc7029650bf2b4fbb7787e93b64556dc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
[package] | |
edition = "2021" | |
name = "hello-wasm" | |
version = "0.1.0" | |
[lib] | |
crate-type = ["cdylib", "rlib"] | |
[dependencies] | |
js-sys = "0.3" | |
wasm-bindgen = "0.2" |
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en-US"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>hello-wasm example</title> | |
</head> | |
<body> | |
<script type="module"> | |
import init, { main } from "./pkg/hello_wasm.js"; | |
init().then(() => { | |
main(); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains hidden or 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
use wasm_bindgen::{prelude::*, JsCast}; | |
#[wasm_bindgen] | |
extern "C" { | |
#[wasm_bindgen(js_namespace = console)] | |
fn log(s: &str); | |
} | |
macro_rules! console_log { | |
($($t:tt)*) => (log(&format_args!($($t)*).to_string())) | |
} | |
#[wasm_bindgen] | |
pub fn main() { | |
// Create an empty object | |
let obj = js_sys::Object::new(); | |
console_log!("Object {:?}", obj); | |
// Firefox: | |
// Object { obj: JsValue(Object({})) } | |
// Set key and value as strings work: | |
let key = JsValue::from_str("key0"); | |
let val = JsValue::from_str("val0"); | |
let success = js_sys::Reflect::set(&obj, &key, &val).unwrap(); | |
console_log!("Object {:?}, success {}", obj, success); | |
// Firefox: | |
// Object { obj: JsValue(Object({"key0":"val0"})) }, success true | |
// Set key as string and value as function does not: | |
let key = JsValue::from_str("key1"); | |
let func: Closure<dyn Fn()> = Closure::wrap(Box::new(|| console_log!("hello from closure"))); | |
let val = func.as_ref().dyn_ref().unwrap(); | |
let success = js_sys::Reflect::set(&obj, &key, val).unwrap(); | |
console_log!("Object {:?}, success {}", obj, success); | |
// Firefox: | |
// Object { obj: JsValue(Object({"key0":"val0"})) }, success true | |
// key1 is missing... although it is accessible | |
let res = js_sys::Reflect::get(&obj, &key).unwrap(); | |
console_log!("Result {:?}", res); | |
// Firefox: | |
// Result JsValue(Function(real)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment