-
Notifications
You must be signed in to change notification settings - Fork 160
/
example_greet_test.go
69 lines (53 loc) · 1.54 KB
/
example_greet_test.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
62
63
64
65
66
67
68
69
package wasmertest
import (
"fmt"
wasm "github.com/wasmerio/go-ext-wasm/wasmer"
"path"
"runtime"
"strings"
)
func greetWasmFile() string {
_, filename, _, _ := runtime.Caller(0)
return path.Join(path.Dir(filename), "testdata", "examples", "greet.wasm")
}
func Example_greet() {
// Instantiate the module.
bytes, _ := wasm.ReadBytes(greetWasmFile())
instance, _ := wasm.NewInstance(bytes)
defer instance.Close()
// Set the subject to greet.
subject := "Wasmer 🐹"
lengthOfSubject := len(subject)
// Allocate memory for the subject, and get a pointer to it.
allocateResult, _ := instance.Exports["allocate"](lengthOfSubject)
inputPointer := allocateResult.ToI32()
// Write the subject into the memory.
memory := instance.Memory.Data()[inputPointer:]
for nth := 0; nth < lengthOfSubject; nth++ {
memory[nth] = subject[nth]
}
// C-string terminates by NULL.
memory[lengthOfSubject] = 0
// Run the `greet` function. Given the pointer to the subject.
greetResult, _ := instance.Exports["greet"](inputPointer)
outputPointer := greetResult.ToI32()
// Read the result of the `greet` function.
memory = instance.Memory.Data()[outputPointer:]
nth := 0
var output strings.Builder
for {
if memory[nth] == 0 {
break
}
output.WriteByte(memory[nth])
nth++
}
lengthOfOutput := nth
fmt.Println(output.String())
// Deallocate the subject, and the output.
deallocate := instance.Exports["deallocate"]
deallocate(inputPointer, lengthOfSubject)
deallocate(outputPointer, lengthOfOutput)
// Output:
// Hello, Wasmer 🐹!
}