-
Notifications
You must be signed in to change notification settings - Fork 54
/
GreetExample.java
60 lines (46 loc) · 1.85 KB
/
GreetExample.java
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
import org.wasmer.Instance;
import org.wasmer.Memory;
import java.io.IOException;
import java.lang.StringBuilder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
class GreetExample {
public static void main(String[] args) throws IOException {
// Instantiates the module.
byte[] bytes = Files.readAllBytes(Paths.get("greet.wasm"));
Instance instance = new Instance(bytes);
Memory memory = instance.exports.getMemory("memory");
// Set the subject to greet.
byte[] subject = "Wasmer".getBytes(StandardCharsets.UTF_8);
// Allocate memory for the subject, and get a pointer to it.
Integer input_pointer = (Integer) instance.exports.getFunction("allocate").apply(subject.length)[0];
// Write the subject into the memory.
{
ByteBuffer memoryBuffer = memory.buffer();
memoryBuffer.position(input_pointer);
memoryBuffer.put(subject);
}
// Run the `greet` function. Give the pointer to the subject.
Integer output_pointer = (Integer) instance.exports.getFunction("greet").apply(input_pointer)[0];
// Read the result of the `greet` function.
String result;
{
StringBuilder output = new StringBuilder();
ByteBuffer memoryBuffer = memory.buffer();
for (Integer i = output_pointer, max = memoryBuffer.limit(); i < max; ++i) {
byte[] b = new byte[1];
memoryBuffer.position(i);
memoryBuffer.get(b);
if (b[0] == 0) {
break;
}
output.appendCodePoint(b[0]);
}
result = output.toString();
}
assert result.equals("Hello, Wasmer!");
instance.close();
}
}