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 and imports map.
imports = %{
env: %{
add_ints: {:fn, [:i32, :i32], [:i32], fn (_context, a, b) -> a + b end},
}
}
{:ok, bytes } = File.read("wasmex_test.wasm")
{:ok, instance } = Wasmex.start_link(%{bytes: bytes, imports: imports})
{:ok, [42]} == Wasmex.call_function(instance, "sum", [50, -8])
The imports are given as a map of namespaces.
In the example above, we import the "env"
namespace.
Each namespace is, again, a map listing imports.
Under the name add_ints
, we imported a 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 - a function reference:
fn (_context, a, b, c) -> a + b end
When the WASM code executes the add_ints
imported function, the execution context is forwarded to
the given function reference.
The first param 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. (There are preparations to enable WASM to return multiple values from a function call. We prepared the API for this future by specifying an array of return types.)