forked from PetterS/clang-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
executable file
·75 lines (66 loc) · 1.85 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
let wasm;
function get_memory() {
return new Uint8Array(wasm.instance.exports.memory.buffer);
}
const decoder = new TextDecoder("utf-8");
const encoder = new TextEncoder("utf-8");
function charPtrToString(str) {
const memory = get_memory();
let length=0;
for (; memory[str + length] !== 0 ;++length) {}
return decoder.decode(memory.subarray(str, str + length));
}
function stringToCharPtr(str) {
const data = encoder.encode(str + "\x00");
const ptr = wasm.instance.exports.get_memory_for_string(data.length + 1);
const memory = get_memory();
memory.subarray(ptr).set(data);
return ptr;
}
function freeCharPtr(ptr) {
wasm.instance.exports.free_memory_for_string(ptr);
}
// If the Webassemby module had been linked with
//
// --import-memory
//
// its memory will be provided with
//
// const wasmMemory = new WebAssembly.Memory({initial:10, maximum:100});
// const memory = new Uint8Array(wasmMemory.buffer);
//
// But this module is providing its own memory and exporting it.
const importObject = {
env: {
print_string: function(str) {
console.log(charPtrToString(str));
}
}
};
WebAssembly.instantiateStreaming(fetch('library.wasm'), importObject)
.then(function(obj) {
wasm = obj;
const s = stringToCharPtr('42');
document.write("<p>string_to_int('42') = " + wasm.instance.exports.string_to_int(s) + "</p>");
freeCharPtr(s);
wasm.instance.exports.factorial(50);
wasm.instance.exports.factorial(100);
wasm.instance.exports.factorial(200);
wasm.instance.exports.factorial(500);
document.write("<p>500! printed to the console. </p>");
document.write(`<p>
<button onclick="wasm.instance.exports.debug_dump_memory();">
Dump memory
</button>
</p>`)
});
</script>
</body>
</html>