TypeScript / JavaScript

WASM integration

Optional Emscripten module contract for a custom JavaScript WASM factory.

This page documents the optional Emscripten module contract used when supplying a custom wasmFactory to Engine.create(). Normal applications use Engine.create() and do not call these module methods. See EngineOptions for the public creation options. Examples that omit setup use the page reference context, which supplies module from the documented release factory and the binding imports.

Interface: WasmModule

TypeScript · interfaceSince v0.10.0
WasmModule
The factory module contract used by the WASM transport. Application code normally lets Engine.create load it.
Fields
HEAPU8Uint8Arrayfield
Current byte view of WASM memory; reacquire it after memory growth.
Methods
Example
console.log('byte view:', module.HEAPU8 instanceof Uint8Array)

Methods

WasmModule._free

TypeScript · methodSince v0.10.0
WasmModule._free
WasmModule._free(
pointer: number
): void
Release a buffer previously reserved in this module.
Arguments
pointernumber
Pointer returned by this module allocation.
Return value
void

Returns no value.

Example
const pointer = module._malloc(4)
if (pointer === 0) throw new Error('Allocation failed')
const returned = module._free(pointer)
console.log('return:', returned)

WasmModule._malloc

TypeScript · methodSince v0.10.0
WasmModule._malloc
WasmModule._malloc(
bytes: number
): number
Reserve a buffer in the module linear memory.
Arguments
bytesnumber
Number of bytes to reserve in linear memory.
Return value
number

Returns a module pointer, or zero when allocation fails.

Example
const pointer = module._malloc(4)
if (pointer === 0) throw new Error('Allocation failed')
try {
  module.HEAPU8.set([65, 66, 67, 0], pointer)
  console.log('bytes:', Array.from(module.HEAPU8.subarray(pointer, pointer + 4)))
} finally { module._free(pointer) }
bytes: [ 65, 66, 67, 0 ]

WasmModule.ccall

TypeScript · methodSince v0.10.0
WasmModule.ccall
WasmModule.ccall(
name: string,
result: string | null,
types: string[],
args: number[]
): number | string
Invoke a named C export through the Emscripten module.
Arguments
namestring
Name of the C export to invoke.
resultstring | null
Emscripten return type, or null for no return value.
typesstring[]
Ordered Emscripten argument type names.
argsnumber[]
Ordered arguments passed to the export.
Return value
number | string

Returns the value of the named export as a number or string. Use null as the return type for an export that returns no value.

Example
const pointer = module.ccall('malloc', 'number', ['number'], [4])
if (typeof pointer !== 'number' || pointer === 0) throw new Error('Allocation failed')
try {
  module.HEAPU8.set([65, 66, 67, 0], pointer)
  console.log('bytes:', Array.from(module.HEAPU8.subarray(pointer, pointer + 4)))
} finally { module.ccall('free', null, ['number'], [pointer]) }
bytes: [ 65, 66, 67, 0 ]

Usage guides