Calling a WebAssembly Function from JavaScript

Learn how to call a WebAssembly function from JavaScript with a simple example adding two integers using inline WAT compiled to WASM binary.

Brief Introduction

Calling a WebAssembly Function from JavaScript (wasm)
DESCRIPTION:
Simple and complete example showing how to write a WebAssembly (WASM) function that adds two integers and how to call it from JavaScript.

ADDITIONAL NOTES:
This example is designed for absolute beginners and uses WebAssembly in text format (WAT) compiled inline to WASM binary via JavaScript for simplicity. In a real project, the WASM file would be compiled separately and loaded as an external file.

EXPLANATIONS:
- The WASM code defines an 'add' function that takes two 32-bit integers and returns their sum.
- JavaScript loads the WASM module, instantiates the module, and calls the 'add' function passing two numbers.
- The result is printed to the browser or Node.js console.
- Comments in the code are in Italian to facilitate understanding.

Example Code: wasm

;; WebAssembly module in text format (WAT) defining an add function
(module
  ;; exports the 'add' function so it can be called from JavaScript
  (func $add (param $a i32) (param $b i32) (result i32)
    ;; adds the two parameters
    local.get $a
    local.get $b
    i32.add
  )
  (export "add" (func $add))
)

// JavaScript to load and use the WASM module
(async () => {
  // Function to convert WAT text to WASM binary
  const watToWasm = async (wat) => {
    // Use WebAssembly.compileStreaming if available, otherwise fallback
    if (typeof WebAssembly.instantiateStreaming === 'function') {
      const encoder = new TextEncoder();
      const wasmModule = await WebAssembly.compile(encoder.encode(wat));
      return wasmModule;
    } else {
      // fallback: use an external or precompiled compiler
      throw new Error('WAT compilation not supported in this environment');
    }
  };

  // For simplicity, we use a precompiled inline array buffer (WASM binary)
  // This is the compiled module of the above WAT (sum of two integers)
  const wasmCode = new Uint8Array([
    0x00,0x61,0x73,0x6d, // magic header
    0x01,0x00,0x00,0x00, // version
    0x01,0x07,0x01,0x60,0x02,0x7f,0x7f,0x01,0x7f,
    0x03,0x02,0x01,0x00,
    0x07,0x07,0x01,0x03,0x61,0x64,0x64,0x00,0x00,
    0x0a,0x09,0x01,0x07,0x00,0x20,0x00,0x20,0x01,0x6a,0x0b
  ]);

  // Instantiate the WASM module
  const wasmModule = await WebAssembly.instantiate(wasmCode);

  // Extract the add function from the exported module
  const add = wasmModule.instance.exports.add;

  // Call the add function with two numbers
  const a = 5;
  const b = 7;
  const result = add(a, b);

  // Print the result
  console.log(`Result of add(${a}, ${b}) = ${result}`);
})();
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Arduino: Not applicable, software-only example.

Software: Node.js or modern browser with WebAssembly support.

Dependencies: No external libraries required.

Configuration: The WASM file must be properly loaded via fetch or import.

Connections: JavaScript uses WebAssembly.instantiateStreaming or WebAssembly.instantiate to load the WASM module.