-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple.go
61 lines (48 loc) · 1.51 KB
/
simple.go
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
57
58
59
60
61
package main
import (
"fmt"
"io/ioutil"
wasmer "github.com/wasmerio/wasmer-go/wasmer"
)
func main() {
// wasmBytes, _ := ioutil.ReadFile("simple.wasm")
wasmBytes, _ := ioutil.ReadFile("./target/wasm32-wasi/debug/example.wasm")
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
// Compiles the module
module, _ := wasmer.NewModule(store, wasmBytes)
wasiEnv, _ := wasmer.NewWasiStateBuilder("example").
Argument("/hello.txt").
Argument("asdf").
MapDirectory("/", ".").
CaptureStdout().
Finalize()
// Instantiates the module
importObject, _ := wasiEnv.GenerateImportObject(store, module)
hostFunction := wasmer.NewFunction(
store,
wasmer.NewFunctionType(wasmer.NewValueTypes(), wasmer.NewValueTypes(wasmer.I32)),
func(argv []wasmer.Value) ([]wasmer.Value, error) {
return []wasmer.Value{wasmer.NewI32(42)}, nil
},
)
importObject.Register(
"hello",
map[string]wasmer.IntoExtern{
"host_function": hostFunction,
},
)
instance, _ := wasmer.NewInstance(module, importObject)
// Gets the `sum` exported function from the WebAssembly instance.
// sum, _ := instance.Exports.GetFunction("sum")
myMain, _ := instance.Exports.GetWasiStartFunction()
res, err := myMain()
fmt.Println(err)
// Calls that exported function with Go standard values. The WebAssembly
// types are inferred and values are casted automatically.
// result, _ := sum(5, 37)
stdout := wasiEnv.ReadStdout()
fmt.Println(string(stdout)) // 42!
fmt.Println(res) // 42!
// fmt.Println(result) // 42!
}