๐ Type-Safe Memory
Full TypeScript support with generics ensures your memory operations are safe at compile time.
Hexagon speed, wasp-lib precision, powered by WASM. A zero-dependency TypeScript library for seamless, type-safe interaction with Emscripten WebAssembly memory.
Working directly with WebAssembly memory from JavaScript is powerful but fraught with challenges like memory leaks, a lack of type safety, and repetitive boilerplate code.
// Manual memory management - error-prone and verbose!
function processData(wasm: any, numbers: number[]) {
// Allocate memory manually
const arraySize = numbers.length * 4; // 4 bytes per i32
const arrayPtr = wasm._malloc(arraySize);
// Copy data byte by byte
for (let i = 0; i < numbers.length; i++) {
wasm.setValue(arrayPtr + i * 4, numbers[i], "i32");
}
// Call WASM function
const sum = wasm._sum_array(arrayPtr, numbers.length);
// Read result and manually free memory
wasm._free(arrayPtr); // Easy to forget!
return sum;
}
wasp-lib
provides intuitive wrapper classes that handle the messy parts of memory management for you, so you can focus on your application logic.
// Clean, type-safe, automatic cleanup!
import { ArrayPointer, WASMModule } from "wasp-lib";
function processData(wasm: WASMModule, numbers: number[]) {
const arrayPtr = ArrayPointer.from(wasm, "i32", numbers.length, numbers);
const sum = wasm._sum_array(arrayPtr.ptr, numbers.length);
// Use readAndFree() for automatic cleanup or free() manually
arrayPtr.free();
return sum;
}