Pass bytes
View SourceThis example sends a binary to a guest, lets the guest change the bytes in place, and reads them back. Numbers pass through a call. Everything else passes through the guest's linear memory: its byte array, which the guest can grow.
You need: nothing beyond the application.
{ok, _} = application:ensure_all_started(wasm).A guest that upper-cases ASCII in place:
Src = ~"""
(module
(memory (export "memory") 1)
(func (export "upper") (param $p i32) (param $n i32) (local $c i32)
(block $done
(loop $next
(br_if $done (i32.eqz (local.get $n)))
(local.set $c (i32.load8_u (local.get $p)))
(if (i32.and (i32.ge_u (local.get $c) (i32.const 97))
(i32.le_u (local.get $c) (i32.const 122)))
(then (i32.store8 (local.get $p)
(i32.sub (local.get $c) (i32.const 32)))))
(local.set $p (i32.add (local.get $p) (i32.const 1)))
(local.set $n (i32.sub (local.get $n) (i32.const 1)))
(br $next)))))
""",
{ok, Mod} = wasm:compile({wat, Src}),
{ok, Inst} = wasm:instantiate(Mod, #{}).Write, call, read:
In = ~"hello, wasm",
ok = wasm:write_memory(Inst, 0, In),
{ok, []} = wasm:call(Inst, ~"upper", [0, byte_size(In)]),
wasm:read_memory(Inst, 0, byte_size(In)).
%% => {ok, ~"HELLO, WASM"}What happened. You chose where the bytes went, address 0, and told the guest the address and the length. Real guests usually decide this themselves, with a fixed buffer or an allocator that they export. Pass data in and out covers both, and JSON.
Clean up:
ok = wasm:destroy(Inst).Read this next
The next example: Run a WASI command. The guide behind this example: Pass data in and out.