wasm-forge-example
A demonstration of WebAssembly integration in Forge applications.
Overview
This example shows:
- Compiling WASM modules with
runtime:wasm - Instantiating and calling WASM functions
- Memory read/write operations
- Module lifecycle management
Features
- Compile WASM from bytes
- Call exported functions with parameters
- Direct memory manipulation
- Multiple module support (add, multiply, memory ops)
Running
forge dev examples/wasm-forge-exampleCapabilities
[capabilities.channels]allowed = ["*"]
[capabilities.wasm]allowed = trueKey Patterns
Compiling WASM
import { compile, instantiate } from "runtime:wasm";
// Compile from bytesconst moduleId = await compile(wasmBytes);
// Instantiate the moduleconst instance = await instantiate(moduleId);Calling Functions
// Get exportsconst exports = await instance.getExports();// Returns: [{ name: "add", kind: "function" }, ...]
// Call a functionconst result = await instance.call("add", 7, 5);console.log(result[0]); // 12Memory Operations
// Write to WASM memoryconst data = new Uint8Array([1, 2, 3, 4]);await instance.memory.write(0, data);
// Read from WASM memoryconst bytes = await instance.memory.read(0, 4);
// Get memory size (in 64KB pages)const pages = await instance.memory.size();Module Cleanup
// Release resources when doneawait instance.drop();Example WASM Modules
Simple Add Function
(module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add))Memory Operations
(module (memory (export "memory") 1) (func (export "get_value") (param i32) (result i32) local.get 0 i32.load) (func (export "set_value") (param i32 i32) local.get 0 local.get 1 i32.store))Architecture
Deno (runtime:wasm) WebAssembly Runtime | | |-- compile(bytes) -------> | Parse & validate | <-- moduleId ------------ | | | |-- instantiate(id) ------> | Create instance | <-- instance ------------ | | | |-- call("add", 7, 5) ----> | Execute | <-- [12] ---------------- | | | |-- memory.write() -------> | Direct memory access | |Extending
Load external WASM files:
import { readBytes } from "runtime:fs";
const wasmBytes = await readBytes("./my-module.wasm");const moduleId = await compile(wasmBytes);const instance = await instantiate(moduleId);