To interact with the current wasm instance's memory buffer, an argument buffer is required.
It should be noted that the necessity of this constructor is not absolute. The binding mentioned pertains to a standard JavaScript API - Uint8Array
- enabling the creation of byte arrays from arbitrary buffers or capacity.
If your aim is simply to pass a byte array view to Rust memory or return bytes in Rust memory to JavaScript, utilize the standard capabilities of wasm-bindgen
instead and pass/return &[u8]
or Vec<u8>
, as you would in regular Rust code.
Nevertheless, to address the latter part of your inquiry
How do I access such an object from the Rust side ? (that gets compiled to wasm)
On the Rust side, you can make use of wasm_bindgen::memory
, which provides a memory instance. When returned by default, it takes the form of a generic JsValue
, although you can convert it into WebAssembly.Memory
using
.unchecked_into::<js_sys::WebAssembly::Memory>()
, thereby granting access to the
buffer
property if necessary.
A built-in API for creating short-lived Uint8Array
views to Rust memory also exists, documented at js_sys::Uint8Array::view
. However, it's labeled as unsafe
due to the potential invalidation of the buffer
upon allocation, triggered by many built-in APIs. Thus, caution must be exercised when handling such views to ensure their immediate utilization after creation. To prevent issues, abstain from relying on low-level access and instead rely on #[wasm_bindgen]
for generating all bindings.