wasm-tool / wasm-pack-plugin

webpack plugin for Rust
MIT License
312 stars 70 forks source link

Cannot access WASM memory #72

Open twop opened 4 years ago

twop commented 4 years ago

I want to get access to WASM module memory similar to https://rustwasm.github.io/book/game-of-life/implementing.html#rendering-to-canvas-directly-from-memory

From the tutorial:

// Import the WebAssembly memory at the top of the file.
import { memory } from "wasm-game-of-life/wasm_game_of_life_bg";

when I try to do that

import { memory } from "../pkg/index_bg";
// same for
import("../pkg/index_bg").then(({memory}) => {..})

i got

    ERROR in ./ts/worker.ts (./node_modules/ts-loader!./ts/worker.ts)
    Module not found: Error: Can't resolve '../pkg/index_bg' in '/Users/twop.sk/work/wp-wasm/ts'
     @ ./ts/worker.ts (./node_modules/ts-loader!./ts/worker.ts) 4:0-41 11:4-10

But index.js file doesn't give access to memory :(

Any workarounds?

alamastor commented 4 years ago

I'm also having this issue. Did you find a solution / workaround?

twop commented 4 years ago

@alamastor Yes, I did, although it is not exactly pretty.

I used wasm-bindgen to expose a memory pointer through a function call. I have an example here:

  1. here I allocate required space in wasm memory: https://github.com/twop/ts-binary-types-workers-demo/blob/master/src/lib.rs#L45
  2. Copy data I need to it in java script : https://github.com/twop/ts-binary-types-workers-demo/blob/master/ts/worker.ts#L42
  3. And then call another wasm function to process the data I passed in: https://github.com/twop/ts-binary-types-workers-demo/blob/master/src/lib.rs#L58

wasm-bindgen allowed me to access these functions via the binding object: https://github.com/twop/ts-binary-types-workers-demo/blob/master/ts/worker.ts#L10 declared here: https://github.com/twop/ts-binary-types-workers-demo/blob/master/src/lib.rs#L39

I'm not sure if it covers your usecase but this is the approach I already used in several projects.

Pauan commented 4 years ago

Yes, the normal way to access Wasm memory in JS is to export a function from Rust which returns a Uint8Array.

If you want to access the entire Wasm memory, you can use the memory function:

#[wasm_bindgen]
pub fn wasm_memory() -> JsValue {
    wasm_bindgen::memory()
}

Now JS can use wasm_memory() to access the entire Wasm linear memory.

alamastor commented 4 years ago

Thanks @twop & @Pauan, that's what I needed, appreciate the help.

andresharpe commented 4 years ago

It also seems to work by adding '.wasm' to the memory import request. Eg:-

import { memory } from "../pkg/index_bg.wasm";