I've set up a WebAssembly environment. What do I need to write to make it work?
I decided to try to make it work with the smallest file size binary in the procedure to generate wasm from asm.js.
Development Environment
asm2wasm.exe and wasm-as.exe
Writing asm.js
function asm(stdlib, foreign, heap) {
'use asm';
const imul = stdlib.Math.imul;
var aa = 0;
function mul(a) {
a = a | 0;
aa = imul(a,a);
return aa;
}
return { mul: mul };
}
Create a function called mul. It squares a given number and returns it.
Generate wast from asm.js
The command line is as follows
asm2wasm.exe mul.js > mul.wast
The generated wast(S formula) is as follows.
(module
(import "env" "memory" (memory $0 256 256))
(import "env" "table" (table 0 0 anyfunc))
(import "env" "memoryBase" (global $memoryBase i32))
(import "env" "tableBase" (global $tableBase i32))
(global $aa (mut i32) (i32.const 0))
(export "mul" (func $mul))
(func $mul (param $a i32) (result i32)
(set_global $aa
(i32.mul
(get_local $a)
(get_local $a)
)
)
(return
(get_global $aa)
)
)
)
There are a few import statements, and if I continue, I get a runtime error.
TypeError: import object field 'env' is not an Object
I'm not sure if this is related to Emscripten, but I'll remove it as follows and proceed.
(module
(global $aa (mut i32) (i32.const 0))
(export "mul" (func $mul))
(func $mul (param $a i32) (result i32)
(set_global $aa
(i32.mul
(get_local $a)
(get_local $a)
)
)
(return
(get_global $aa)
)
)
)
wast to wasm generation
The command line is as follows
wasm-as.exe mul.wast -o mul.wasm
The generated wasm is binary. Only 80 bytes.
00,61,73,6D,01,00,00,00,01,86,80,80,80,00,01,60,
01,7F,01,7F,03,82,80,80,80,00,01,00,06,86,80,80,
80,00,01,7F,01,41,00,0B,07,87,80,80,80,00,01,03,
6D,75,6C,00,00,0A,95,80,80,80,00,01,8F,80,80,80,
00,00,02,7F,20,00,20,00,6C,24,00,23,00,0F,0B,0B,
Writing html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button type="button" id="run">Run</button>
<div id="result"></div>
<script>
const module = fetch('mul.wasm')
.then(x => x.arrayBuffer())
.then(x => WebAssembly.compile(x));
document.getElementById('run').addEventListener('click',function() {
module.then(x => {
const instance = new WebAssembly.Instance(x, {});
const result = instance.exports.mul(7);
document.getElementById('result').innerHTML = result;
});
},false);
</script>
</body>
</html>
After loading HTML and executing Script, mul.wasm is loaded and ready to use.
Clicking the "Run" button will pass the number 7 to the mul function of WASM, and the result will be returned and displayed.
If 49 (7x7) is displayed, it is a success.