Lets write your first wasm program

Lets write your first wasm program

Introduction

WebAssembly, commonly referred to as WASM is the fourth language web browser can understand. It promises a fast, safe and efficient language for client and server applications. One of the most promising features of WASM is that code written in any other language can be ported to wasm code so that we can execute it directly in a web browser, it's like writing code in C++ and executing it in the browser directly!!. So in today's article, we are going to write about your first WASM program.

Setting up environment

To write code in wasm we need

  • A standard code editor - It can be any code editor of your choice.

  • Emscripten - It is a compiler toolchain which converts code written in C/C++ in WebAssembly. you can download and install it from here.

Writing & Compiling Code

We are going to write our code in C++ and convert it to wasm code using Emscripten.

#include<emscripten.h>
#include<iostream>
using namespace std;

extern "C"{

// returns factorial of a number
EMSCRIPTEN_KEEPALIVE
unsigned long long int fact(int num){
    if(num > 1) {
        unsigned long long int result =  num * fact(num-1);
        std::cout<<num<<" "<<result<<std::endl;
        return result;
    }
    return 1;
}


// converts factorial to string
EMSCRIPTEN_KEEPALIVE
char const* factorial(int num){
    std::string result = std::to_string(fact(num));
     char const* output = result.c_str();
     return output;
}
}

in the above code snippet as you can see we have a simple function fact which will give us the factorial of a number given as input and another function factorial which will convert your factorial to a string so that we get a string directly in the JavaScript side. You can see a keyword EMSCRIPTEN_KEEPALIVE which tells the Emscripten to include this function in the output file and extern "C" which tells the Emscripten to preserve the names of the functions.

em++ code.cpp -o function.js -sEXPORTED_RUNTIME_METHODS=['ccall'] -sMODULARIZE

Now open a command line in the same directory as your file and write the command written above. meaning of each keyword is explained below.

  1. em++ - executes the emscripten

  2. code.cpp - the name of your C++ file

  3. -o function.js - any JavaScript or HTML or WASM file name following the -o specifies the file name and file type of the output.

  4. -sEXPORTED_RUNTIME_METHODS=['ccall'] - this keyword let us specify which function provided by the Emscripten we want in our output code.

  5. -sMODULARIZE - this keyword makes the output file a module which makes it easy to import and use in our code.

the following command will output 2 files - function.js and function.wasm, function.wasm contains the wasm code and function.js contains the necessary code to import and initialize the wasm module so that we don't have to.

Creating frontend

Now as we have our wasm code ready now let's create our basic frontend to execute the code.

First of all, include the function.js file in the head section of your HTML page

 <script src="./wasm/function.js"></script>

Add an input, a button and a text element to show the output.

 <input type="number" id="input">
 <button type="button" id="show_output">factorial</button>
 <p id="output"></p>

Now let's add our script where we are going to call our factorial function from C++.

// Module is the promise which resolves to the WASM module. 
Module().then((mod) => {
        let show_output = document.getElementById("show_output");
        let input = document.getElementById("input");
        let output = document.getElementById("output");
        // adding event listener
        show_output.addEventListener("click", function () {
        // calling the fact function using ccall 
          output.innerText = mod.ccall(
            "factorial",
            "string",
            ["number"],
            [Number(input.value)]
          );
        });
      });

Here we add an event listener to the button, upon clicking we are taking the value from the input field and then call the factorial function using ccall which we exported from during the compiling phase. Its syntax is like this

Module.ccall(function_name,return_type,[..args_type],[..args]);

Output

Now host your website on a local server and navigate to the website. Now enter some value in the input field and click the button to show the output.

You can find more details here.

If you have any questions ask me in the comments. Thanks for reading ❤

output screen