Access WebAssembly Memory Directly from JavaScript

Share this video with your friends

Send Tweet

While JavaScript has a garbage-collected heap, WebAssembly has a linear memory space. Nevertheless using a JavaScript ArrayBuffer, we can read and write to WebAssembly’s memory space.

NK
NK
~ 5 years ago

Looks like there's been some reshuffling of directories, so rather than using

import { memory } from "../crate/pkg/rust_webpack_bg";
import { Image } from "../crate/pkg/rust_webpack";

I imported content from the wasm-pack-generated files into app.js using:

import { memory } from "../pkg/index_bg";
import { Image } from "../pkg/index";
Andrey Kolybelnikov
Andrey Kolybelnikov
~ 5 years ago

The const pixels = new Uint8Array(memory.buffer, pixelsPointer, 6) is always [0,0,0,0,0,0] in my case. I can't figure out what's going on, because the const pixelsPointer = image.pixels_ptr() is not empty, but it is of type number. Should it be an array of numbers? It's a vec on the Rust's side. Because of the newer version of the template generator, memory is not explicitly exported in pkg and I have to construct it: const memory = new WebAssembly.Memory({ initial: 256 }). Could this be the issue?

Andrey Kolybelnikov
Andrey Kolybelnikov
~ 5 years ago

I have found out that to use the memory exported from warm-pack we need to run was-pack build and import the memory in app.js like so: import { memory } from '../pkg/index_bg'. The rest of the syntax is intact.