wasm
provides utilities for loading and running wasm modules
built on top of the wasmer runtime.
setup
start by installing the tools needed to build the wasmer runtime:
- install the rust sdk.
- on windows, to get
link.exe
, install the visual studio build tools
with the “desktop development with c++”-option selected.
basic usage
as a simple example, we’ll try to call a simple c function from dart using
package:wasm
. for a more detailed example that uses wasi, check out the
example directory.
- first create new dart app folder:
dart create wasmtest
- add a dependency to package
wasm
inpubspec.yaml
and rundart pub get
- next run
dart run wasm:setup
to build the wasmer runtime. this will take a few minutes. - then add a new file
square.cc
with the following contents:extern "c" int square(int n) { return n * n; }
- we can compile this c++ code to wasm using a recent version of the
clang compiler:clang --target=wasm32 -nostdlib "-wl,--export-all" "-wl,--no-entry" -o square.wasm square.cc
- replace the contents of your dart program (
bin/wasmtest.dart
) with:import 'dart:io'; import 'package:wasm/wasm.dart'; void main() { final data = file('square.wasm').readasbytessync(); final mod = wasmmodule(data); print(mod.describe()); final inst = mod.builder().build(); final square = inst.lookupfunction('square'); print(square(12)); }
- run the dart program:
dart run
. this should print:export memory: memory export function: int32 square(int32) 144
Comments are closed.