-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.html
61 lines (51 loc) · 2.25 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MiniWASM</title>
</head>
<body>
<h1>MiniWASM</h1>
<p>Open the development console to see log messages.</p>
<script>
class MiniBridge {
async bootstrap(url) {
// Fetch wasm file
const response = await fetch(url);
if (!response.ok) {
throw Error("Error loading wasm file: " + response.status);
}
// Instantiate WebAssembly context
const data = await response.arrayBuffer();
const webAssembly = await WebAssembly.instantiate(data, {
env: {
console_log: this.extractString(console.log),
console_error: this.extractString(console.error)
}
});
// Grab the wasm instance and its memory (wrapped in an Uint8Array)
this.wasm = webAssembly.instance;
this.buffer = new Uint8Array(this.wasm.exports.memory.buffer);
// Call the wasm module's entry point
this.wasm.exports.initialize();
}
extractString = fn => (ptr, len) => {
// Get a fresh Uint8Array if the wasm memory buffer was moved
const buffer = this.wasm.exports.memory.buffer;
if (this.buffer !== buffer) {
this.buffer = new Uint8Array(buffer);
}
// Make a string from the slice of memory and pass it into fn
fn(String.fromCharCode.apply(null, this.buffer.slice(ptr, ptr + len)));
}
}
const bridge = new MiniBridge();
bridge.bootstrap("miniwasm.wasm").then(function() {
console.log("Bootstrap completed, now go build something awesome!");
// Call example function
const value = bridge.wasm.exports.hello(256);
console.log("The value returned by hello() was " + value);
});
</script>
</body>
</html>