Skip to main content

Runtime WASM Loading

The basic use of Wasmbox has a WASM/WAT file imported in the editor, to produce a WasmAsset which can be loaded at runtime. However sometimes it is necessary to load a WASM file at runtime, for example loading mods from a folder. This can be done with the DynamicWasmAsset or a custom IWasmAsset.

Dynamic Wasm Asset

The DynamicWasmAsset provides a way to create a WasmAsset at runtime from a file that was never processed in the editor. It can be loaded from raw WASM bytes, or Web Assembly Text format.

WASM Bytes

A DynamicWasmAsset can be loaded from WASM bytes stored in memory, or in a file.

Loading WASM from a byte array
byte[] some_wasm_bytes = GetWasmFromSomewhere();
DynamicWasmAsset.FromWASM(some_wasm_bytes);

WAT Text

A DynamicWasmAsset can be loaded from WAT text stored in memory, or in a file.

Loading WAT from a string
string wat = "(module (memory 1) (func))";
DynamicWasmAsset.FromWAT(wat);

Caching

When a WasmAsset is compiled into a LoadedModule it is cached in memory, to speed up subsequent loads of the same asset. A DynamicWasmAsset may opt-in to this behaviour by setting the cacheKey. The loaded module will be cached under this unique ID, later attempts to load another asset with the same cache key will load the original module.

tip

Only enable caching if the same module is likely to be reloaded several times.

danger

Do not enable caching if is possible for the module to change!

More Customisation

If a DynamicWasmAsset does not meet your use-case, consider creating a custom IWasmAsset implementation. This will give you complete control over how a Module is constructed.