Skip to content Skip to sidebar Skip to footer

Rust Wasm: How To Access Webassembly.memory Of Current Instance (from Rust)?

Looking at the function signature of js_sys::Uint8Array::new_with_byte_offset_and_length pub fn new_with_byte_offset_and_length( buffer: &JsValue, byte_offset: u32,

Solution 1:

It needs an argument buffer which refers to the current wasm instance's memory buffer.

First of all, it's worth noting that this is not necessarily true. That binding is for a standard JavaScript API - Uint8Array - which allows you to create byte arrays from arbitrary buffers or capacity.

You don't really need this constructor if you just want to pass a byte array view to Rust memory or return bytes in a Rust memory to JavaScript - for that, instead use wasm-bindgen's standard capabilities and pass/return &[u8] or Vec<u8> like you would in regular Rust code.

However, to answer your second part of the question just in case

How do I access such an object from the Rust side ? (that gets compiled to wasm)

From the Rust side you can use wasm_bindgen::memory, which will give you a memory instance. By default it returns it as a generic JsValue, but you can cast it into WebAssembly.Memory using .unchecked_into::<js_sys::WebAssembly::Memory>(), which, in turn, will let you access the buffer property should you need it.

Note that creating short-lived Uint8Array views to Rust memory like that is also implemented in a built-in API js_sys::Uint8Array::view, but it's marked unsafe for a good reason: buffer can get invalidated on any allocation, which lots of built-in APIs invoke, so you need to handle such views very carefully and make sure that they are used immediately after creation. Best way to avoid issues is, again, not relying on such low-level access at all, and instead using #[wasm_bindgen] to generate any bindings.

Post a Comment for "Rust Wasm: How To Access Webassembly.memory Of Current Instance (from Rust)?"