mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-14 13:31:22 +00:00
Changing wasm-in-wasm example to be async (#1903)
This commit is contained in:
@ -10,3 +10,4 @@ crate-type = ["cdylib"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
wasm-bindgen = "0.2.55"
|
wasm-bindgen = "0.2.55"
|
||||||
js-sys = "0.3.32"
|
js-sys = "0.3.32"
|
||||||
|
wasm-bindgen-futures = "0.4.5"
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
use js_sys::{Function, Object, Reflect, Uint8Array, WebAssembly};
|
use js_sys::{Function, Object, Reflect, WebAssembly};
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
use wasm_bindgen::JsCast;
|
use wasm_bindgen::JsCast;
|
||||||
|
use wasm_bindgen_futures::{spawn_local, JsFuture};
|
||||||
|
|
||||||
// lifted from the `console_log` example
|
// lifted from the `console_log` example
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
@ -15,24 +16,12 @@ macro_rules! console_log {
|
|||||||
|
|
||||||
const WASM: &[u8] = include_bytes!("add.wasm");
|
const WASM: &[u8] = include_bytes!("add.wasm");
|
||||||
|
|
||||||
#[wasm_bindgen(start)]
|
async fn run_async() -> Result<(), JsValue> {
|
||||||
pub fn run() -> Result<(), JsValue> {
|
|
||||||
console_log!("instantiating a new wasm module directly");
|
console_log!("instantiating a new wasm module directly");
|
||||||
|
|
||||||
// Note that `Uint8Array::view` is somewhat dangerous (hence the
|
let a = JsFuture::from(WebAssembly::instantiate_buffer(WASM, &Object::new())).await?;
|
||||||
// `unsafe`!). This is creating a raw view into our module's
|
let b: WebAssembly::Instance = Reflect::get(&a, &"instance".into())?.dyn_into()?;
|
||||||
// `WebAssembly.Memory` buffer, but if we allocate more pages for ourself
|
|
||||||
// (aka do a memory allocation in Rust) it'll cause the buffer to change,
|
|
||||||
// causing the `Uint8Array` to be invalid.
|
|
||||||
//
|
|
||||||
// As a result, after `Uint8Array::view` we have to be very careful not to
|
|
||||||
// do any memory allocations before it's dropped.
|
|
||||||
let a = unsafe {
|
|
||||||
let array = Uint8Array::view(WASM);
|
|
||||||
WebAssembly::Module::new(array.as_ref())?
|
|
||||||
};
|
|
||||||
|
|
||||||
let b = WebAssembly::Instance::new(&a, &Object::new())?;
|
|
||||||
let c = b.exports();
|
let c = b.exports();
|
||||||
|
|
||||||
let add = Reflect::get(c.as_ref(), &"add".into())?
|
let add = Reflect::get(c.as_ref(), &"add".into())?
|
||||||
@ -51,3 +40,10 @@ pub fn run() -> Result<(), JsValue> {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen(start)]
|
||||||
|
pub fn run() {
|
||||||
|
spawn_local(async {
|
||||||
|
run_async().await.unwrap_throw();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user