Wasmex.start_link
start_link
, go back to Wasmex module for more information.
start_link(bytes)
Starts a GenServer which compiles and instantiates a WASM module from the given bytes.
{:ok, bytes } = File.read("wasmex_test.wasm")
{:ok, instance } = Wasmex.start_link(bytes)
{:ok, [42]} == Wasmex.call_function(instance, "sum", [50, -8])
start_link(bytes, list)
Starts a GenServer which compiles and instantiates a WASM module from the given bytes with additional options.
Imports
Imports are provided as a map of namespaces, each namespace being a nested map of imported functions:
imports = %{
env: %{
add_ints: {:fn, [:i32, :i32], [:i32], fn (_context, a, b) -> a + b end},
}
}
{:ok, instance } = Wasmex.start_link(bytes, imports: imports)
In the example above, we import the "env"
namespace.
Each namespace is a map listing imports, e.g. the add_ints
function
which is represented with a tuple of:
- the import type:
:fn
(a function), - the functions parameter types:
[:i32, :i32]
, - the functions return types:
[:i32]
, and - the function to be executed:
fn (_context, a, b, c) -> a + b end
The first param the function receives is always the call context (a Map containing e.g. the instances memory). All other params are regular parameters as specified by the parameter type list.
Valid parameter/return types are:
:i32
a 32 bit integer:i64
a 64 bit integer:f32
a 32 bit float:f64
a 64 bit float
The return type must always be one value.
WASI
Optionally, modules can be run with WebAssembly System Interface (WASI) support. WASI functions are provided as native NIF code by default.
{:ok, instance } = Wasmex.start_link(bytes, wasi: true)
It is possible to overwrite the default WASI functions using imports as described above.
Oftentimes, WASI programs need additional input like environment variables or arguments.
These can be provided by giving a wasi
map:
wasi = %{
args: ["hello", "from elixir"],
env: %{
"A_NAME_MAPS" => "to a value",
"THE_TEST_WASI_FILE" => "prints all environment variables"
}
}
{:ok, instance } = Wasmex.start_link(bytes, wasi: wasi)
It is also possible to capture stdout, stdin, or stderr of a WASI program using pipes:
{:ok, stdin} = Wasmex.Pipe.create()
{:ok, stdout} = Wasmex.Pipe.create()
{:ok, stderr} = Wasmex.Pipe.create()
wasi = %{
stdin: stdin,
stdout: stdout,
stderr: stderr
}
{:ok, instance } = Wasmex.start_link(bytes, wasi: wasi)
Wasmex.Pipe.write(stdin, "Hey! It compiles! Ship it!")
{:ok, _} = Wasmex.call_function(instance, :_start, [])
Wasmex.Pipe.read(stdout)