summaryrefslogtreecommitdiff
path: root/inter/main.go
blob: ee0d463a97523af5a09c9232df90900139614fdc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/tetratelabs/wazero"
	"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)

const wasmLocation = "../hello.wasm"

func main() {
	var ctx = context.Background()

	var runtime = wazero.NewRuntime(ctx)
	defer runtime.Close(ctx)

	var _, hostErr = runtime.NewHostModuleBuilder("env").
		NewFunctionBuilder().
		WithFunc(xdx).
		Export("xdx").
		Instantiate(ctx);
	if hostErr != nil {
		panic(fmt.Sprintf("Failed to create host module: %s", hostErr.Error()))
	}

	wasi_snapshot_preview1.MustInstantiate(ctx, runtime)

	var wasm, wasmErr = LoadWasm()
	if wasmErr != nil {
		panic(fmt.Sprintf("Failed to load WASM module: %s", wasmErr.Error()))
	}

	var mod, modErr = runtime.Instantiate(ctx, wasm)
	if modErr != nil {
		panic(fmt.Sprintf("Failed to instantiate WASM module: %s", modErr.Error()))
	}

	var add = mod.ExportedFunction("Add")
	var result, callErr = add.Call(ctx, 9, 10)
	if callErr != nil {
		panic(fmt.Sprintf("Failed to call WASM finction: %s", callErr.Error()))
	}
	fmt.Printf("Addition result: %v\n", result[0])
}

func LoadWasm() ([]byte, error) {
	return os.ReadFile(wasmLocation)
}

func xdx() {
	log.Printf("xdx (called from WASM)")
}