Using WASM fiddle, we show how to write a simple number logger function that calls a ConsoleLog function defined in JAVASC Ript. We then download and run the same function in a local project.
WASM FIDDLE:HTTPS://WASDK.GITHUB.IO/WASMFIDDLE/?CVRMT
Demo Repo:https://github.com/guybedford/wasm-intro
Basiclly WASM is hard-to-debug, we still need JavaScript to help, the "the"-do debugging is we pass Javascript Console.lo g function into WASM though "imports". Defined a C code:
#include <math.h>void consolelog (float num); float getsqrt (float num) { consolelog (num); return sqrt (num);}
Defined a function called "ConsoleLog".
After build to Wasm:
( module (Type $FUNCSIG $vf (func (param F32))) (Type $FUNCSIG $ff (func (param f32) (Result f32)) (Import "env " "ConsoleLog" (func $consoleLog (param f32 ))) (Table0Anyfunc) (Memory $0 1) (Export"Memory"(Memory $0)) (Export"getsqrt"(func $getSqrt)) (Func $getSqrt (param $0F32) (Result F32) (Call $consoleLog (get_local $0)) (F32.SQRT (get_local $0) ) ))
It ' s importing ConsoleLog from a module called environment.
This is just a default module namespace name for the externals of a C code compilation process.
Now on JS side, we need to pass the Console.log function from "Imports" param:
functionfetchandinstantiatewasm (URL, imports) {returnfetch (URL). Then (RES)= { if(Res.ok) {returnRes.arraybuffer (); } Throw NewError (' Unable to fetch WASM ')}). Then ((bytes)= { returnwebassembly.compile (bytes); }). Then (module= { returnWebassembly.instantiate (module, imports | | {}); }). Then (instance=instance.exports); } fetchandinstantiatewasm ('./program.wasm ', {env: {consolelog: (num) = console.log (num)}}) . Then (M={window.getsqrt=m.getsqrt; });
[WASM] Call a JavaScript Function from WebAssembly