[WASM] Call a JavaScript Function from WebAssembly

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.