Emscripten: Customize the generated js so it loads the .wasm file in a custom way

Viewed 512

By compiling with the following options,

emcc -s WASM=1 main.cpp -o index.js

emscripten generates an index.wasm, and a js wrapper index.js. The js wrapper loads the .wasm file located in the same directory, using XMLHttpRequest when it's running in a browser.

So what should I do if I need to load of the .wasm file manually? The loading part seems hard-coded in the wrapper.

Here are some circumstances where I need this:

  • I need to serve the .wasm file from another url (for example from CDN).
  • The url to download the .wasm file is dynamically generated.
  • The code is running in a sandbox where XMLHttpRequest is not allowed, there is only an API like getMyData('some_file').
  • I need to embed all the files as base64 string.

I know I could generate the .wasm file only, by

emcc -s WASM=1 main.cpp -o index.wasm

But then I loses the wrapper, which is not trivial when using some emscripten APIs like SDL and GLES.

1 Answers

AFIK, the JS wrapper calls fetch() and not XHR. If available, you could use a Service Worker to intercept that request and return whatever you'd like.

You could also modify the Emscripten source (I have v1.39.13) to rewrite the default loading behavior. In file $EMSDK/upstream/emscripten/src/preamble.js, modify functions getBinaryPromise() and getBinary() to your liking, then build with emcc to have your custom loading behavior in the WASM JS wrapper.

Related