5

Is it possible to pass javascript callback to WebAssembly? Can we trigger an event from WebAssembly and listen to it in javascript?

Shula
  • 167
  • 1
  • 18

2 Answers2

5

I found this article from Kevin Hoffman attempting this using rust.

It boils down to using WebAssembly.instantiate(bufferSource, importObject) optional importObject. You can read more about this on MDN.

Here is the example for the article

Web Client

<html>
 <head>
  <script>

   function logit() {
     console.log('this was invoked by Rust, written in JS');
   }

   let imports = {logit};

   fetch('wasm_project.gc.wasm')
     .then(r => r.arrayBuffer() )
     .then(r => WebAssembly.instantiate(r, { env: imports }))
     .then(wasm_module => {
       alert(`2 + 1 = ${wasm_module.instance.exports.add_one(2)}`);
     });
   </script>

 </head>
 <body></body>
</html>

Rust prototype

extern "C" {
   fn logit();
}

Rust

#[no_mangle]
pub extern fn add_one(a: u32) -> u32 {
    logit();
    a + 1
}

Credit

All credit goes to Kevin Hoffman's Article

Michael Warner
  • 3,879
  • 3
  • 21
  • 45
1

You can, but you have to use a function table from the webassembly side. What it does its just referencing functions by index in a table and calling them with a dynamic index using call_indirect.
Note: The table is a core thing of webassembly but I don't know how it is implemented in other languages other than WebAssembly-Text (wat). The call_indirect is the binary instruction's name

faBri_CI-o
  • 53
  • 1
  • 6