简体   繁体   中英

How do I detect when Emscripten's generated .js finishes loading the wasm so I can run my JS functions which call it?

I'm using Emscripten to compile some C code to WebAssembly. This is the final emcc call in my Makefile:

emcc $(CFLAGS) iva.a -o iva.js

Which works as intended and generates a.js file and a.wasm file. The JS is loaded into my HTML page as follows:

<script src="../dist/iva.js">

And it loads and instantiates the WebAssembly code iva.wasm properly. This message appears in the console soon after I load the page:

Fetch finished loading: GET "http://localhost:6931/dist/iva.wasm".

Which I take to mean that my WebAssembly is loaded through a fetch() and, perhaps pending some processing, I can access my functions through the console:

Module._init_display_system()

And get the return values. This holds true and everything works.

Clearly, I should be able to do this through a script as well. However, I can't see a way to only run a function after my WebAssembly has been instantiated. I get the feeling that I'm missing something rather obvious.

Anyway, how do I do this?

Use Module['onRuntimeInitialized'] .

Module['onRuntimeInitialized'] = function() {
       console.log("wasm loaded ");
       var x=Module.ccall("doubleIt","number",["number"],[20]);
       alert(x);
    }

You have used emsdk, there are online WASM compilers like Wasmfiddle. Find my github repo useful for both the methods.

While the two solutions of Sudhakar RS and Anil8753 are totally fine, I want to add, that you have to execute this approach before you load your WebAssembly. Otherwise it might be too late to catch the event.

Besides that, there is another approach, which uses promises. If you add

-s MODULARIZE=1 -s 'EXPORT_NAME="createMyModule"'

as options when compiling with emcc , your resulting .js will contain the function createMyModule . This function will return a Promise that resolves as soon as your WebAssembly code is ready to use. Example usage:

In your HTML, add your WebAssembly as you already did:

<script src="../dist/iva.js">

In your js, call the function and after the promise resolved, you are good to go:

createMyModule().then(MyModule => {
  console.log('WebAssembly loaded!');
  // Access your functions (if bound by Embind):
  console.log(MyModule.getSomething());
});
  <script>
    var Module = {
      onRuntimeInitialized: function() {
         console.log('module loaded');
      }
    };
  </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM