What is @assemblyscript/loader?
The @assemblyscript/loader package is designed to load and instantiate WebAssembly modules compiled from AssemblyScript. It provides a convenient API for interacting with WebAssembly instances, including memory management, table imports, and handling complex data types like strings and arrays.
What are @assemblyscript/loader's main functionalities?
Instantiating WebAssembly Modules
This feature allows you to synchronously instantiate a WebAssembly module from a buffer containing the compiled binary. The second argument is an object that can contain imports required by the WebAssembly module.
const loader = require('@assemblyscript/loader');
const wasmModule = loader.instantiateSync(fs.readFileSync('myModule.wasm'), { /* imports */ });
const exports = wasmModule.exports;
Memory Management
The loader provides functions to manage memory within the WebAssembly module, such as allocating and freeing memory, and garbage collection. This is useful for managing the lifecycle of objects and preventing memory leaks.
const { __new, __pin, __unpin, __collect } = wasmModule.exports;
const ptr = __new(size, id);
__pin(ptr);
// Use the pointer
__unpin(ptr);
__collect();
Interacting with Complex Data Types
The loader offers utility functions to create and read complex data types like strings. This allows for easy passing of strings between JavaScript and WebAssembly.
const { __getString, __newString } = wasmModule.exports;
const strPtr = __newString('Hello, World!');
const str = __getString(strPtr);
Other packages similar to @assemblyscript/loader
wasm-bindgen
wasm-bindgen is a tool and library for facilitating high-level interactions between Wasm modules and JavaScript. It allows one to import JavaScript things into Rust and export Rust things to JavaScript. It's similar to @assemblyscript/loader but is designed for Rust rather than AssemblyScript.
emscripten
Emscripten is a toolchain for compiling to asm.js and WebAssembly, built using LLVM. It allows you to compile C and C++ code to WebAssembly and run it on the web. While it serves a similar purpose in compiling to WebAssembly, it is more of a compiler toolchain than a loader and is used with different source languages.
wasm-loader
wasm-loader is a webpack loader that imports WebAssembly modules. It's similar to @assemblyscript/loader in that it helps with loading WebAssembly modules, but it's integrated into the webpack build process and doesn't provide the same level of API for interacting with the WebAssembly module.