2

In webassembly.org, JS API page, the way to import WebAssembly in javascript is

fetch('example.wasm').then(response => response.arrayBuffer())
.then(bytes => instantiate(bytes, importObject))
.then(instance => instance.exports.e());

The js file emitted by emcc seems to do that.

But when I use wasm-pack for Rust's Cargo, the javascript file simply does import * as wasm from './example.wasm'

What's the difference between these two? Is direct import a newly supported feature? and when using the direct import how would I access WebAssembly's memory from javascript since I didn't pass them to the WebAssembly module as I would do if I used the first method?

1
  • 1
    I believe your various questions are answered here, but I haven't gotten deep enough into it to post a complete answer based on that. Commented Sep 22, 2019 at 12:38

2 Answers 2

3

The declarative import of WebAssembly modules is not yet standardized. I assume wasm-pack targets the experimental import feature of Node.js: http://web.archive.org/web/20220528033110/https://www.joyent.com/blog/improved-wasm-support-coming-to-node#importing-webassembly-modules

How to access the memory depends on the module: if it exports it, you can access it as a member, if it imports it, it has to be available as a member of an ES6 module under the names you would use in the import object.

Sign up to request clarification or add additional context in comments.

Comments

1

Depending on the platform, if wasm module is running in a web browser, fetch and instantiate as mention in question. WASI has enabled to provide even files system sandboxing also when running WASM in nodejs. which can read the file from disk using node Fs in instantiate using WASI

    const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
    const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
    const instance = await WebAssembly.instantiate(wasm, importObject);
    wasi.start(instance);

link: https://nodejs.org/api/wasi.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.