From Lazarus wiki
Revision as of 18:23, 5 September 2019 by Skalogryz (talk | contribs) (Using Wasm Functions)

The primary target for WebAssembly is the browser.

WebAssembly is not a Javascript, it's only an addition to Javascript.

WebAssembly is not asm.js.


The primary API for dealing with WebAssembly (.wasm) files is WebAssembly JS standard

Using Wasm Functions

In order to use a .wasm file in Javascript the following steps needs to be taken

  • .wasm file needs to be loaded
  • as an external resource (a web server is required due to browsers security)
  • a binary file loaded throw a javascript (i.e. inlined).
  • loaded .wasm binary file needs to be compiled
  • the compiled file needs to be linked (aka instantiated). It's also common to do the compilation and instantiation in one steps, rather than two separate steps. (Two separate steps are typically needed, when "compiled" form would be used, either for caching OR for dependencies resolution stage)
  • when creating an instance (linking) all dependencies must be resolved.
  • after creating an instance, the exported functions of the instance can be called through Javascript, as a normal JS functions.

Here's a common JS example

// step #1 - loading the file and converting it to array of bytes, using fetch() function
  response => response.arrayBuffer()
  // step #2 and 3 - compiling and linking array of bytes (in one call) to WebAssembly.instantiate()
  bytes => WebAssembly.instantiate(bytes)).then(results => {

  // step #4 using the linked instance object to call the exported function add()
  instance = results.instance;
  document.getElementById("container").textContent = instance.exports.add(1,1);


As of 2019 there's no "out-of-the-box" way to resolve WebAssembly file import dependencies.

WebAssembly expects an import to be resolved by providing the import module name. The import module name doesn't have to be a WebAssembly module, it can be a plain JavaScript function as well. And the name of the object (i.e. function of memory) WebAssembly is trying to access.


Here's an example of dependencies loading.

WARNING: you should NOT use this code in production. It's only used for educational purposes! Javascript and it's APIs are designed to do all the tasks asynchronously. Most of the code is based on the callbacks (closures), that are triggered when the particular task is done. I.e. loading a resources from the web, would trigger an event once the loading is completed (or failed).

Javascript language has been updated with additional syntax to support it. i.e.

fetch('../out/main.wasm').then(response =>
).then(bytes => WebAssembly.instantiate(bytes)).then(results => {
  instance = results.instance;
  document.getElementById("container").textContent = instance.exports.add(1,1);

The example below is intentionally performs each step synchronously (by using "await" syntax is used to explicitly wait for a completion of synchronous actions). Such intentional synchronization would impose slowness in a real-life application and should not be used.

The example consists of two WebAssembly files and a single Javascript file to load them.


The module imports function named "add" from an external module named "test2"


(import "test2" "add" (func $add (param i32)(param i32)(result i32) ))

;; the main() function calls the external add() with arguments 4 and 5 
;; and forwards the result of add as it's own result
(func $main
  (result i32)
    i32.const	4
    i32.const	5
    call	$add
;; module exports the main function so it can be called outside (in javascript)
(export "main" (func $main))


The module implements "add" function and exports it.

  (func $add (param $lhs i32) (param $rhs i32) (result i32)
    get_local $lhs
    get_local $rhs
  (export "add" (func $add))


async function runWasm()
   var r = await fetch('../out/main.wasm'); // Promise() object handling getting of the file
   var bytes = await r.arrayBuffer();
   var mainmod = await WebAssembly.compile(bytes);
   // console.log(mainmod); // print the main module
   var impobj = {};
   var imports = WebAssembly.Module.imports(mainmod);
   // console.log(imports); // print dependencies list
   var loadedInst = [];

   // loading dependencies should be recursive!
   for (var i = 0; i < imports.length; i++)
      var dep  = imports[i];

      var subinst = loadedInst[dep.module];
      if (!subinst) 
        var rr = await fetch('../out/'+dep.module+'.wasm');
        var buf = await rr.arrayBuffer();
        var submod = await WebAssembly.instantiate(buf);
        subinst = submod.instance;
        loadedInst[dep.module] = subinst;
      //console.log(subinst); // print the sub module instance

      var impmod = impobj[dep.module];
      if (!impmod) {
        impmod = {};
        impobj[dep.module] = impmod;
      impmod[dep.name] = await subinst.exports[dep.name];
      impobj[dep.module] = impmod;
   // console.log(impobj); // print of imported object object

   var maininst = await WebAssembly.instantiate(mainmod, impobj);
   // console.log(maininst); // print of the main instance object

   // calling the main() function of the main unit
   document.getElementById("container").textContent = maininst.exports.main();

See Also