Web assembly introduction

In today’s blog we introduce webassembly via a simple c/c++ program and showcase how powerful this paradigm is.

So what is web assembly-

Web assembly is a binary instruction format. Its designed for stack based virtual machines. It’s a portable format and allows language runtimes like C++, Rust, Golang to be compiled to the webassembly. The web assembly format can be invoked by runtimes like v8, which opens up interesting paradigms. As an example now we can write a Rust program and compile it to web assembly and execute it in browser. The same can be invoked server side by programs using v8 engine like nodejs.

Web assembly format (also called wasm) is optimized for size and load time. This provides faster execution times for web based applications.

Today we take example of a simple c program and generate the wasm and then execute it in the chrome browser.

To do this we need the emscripten tool which we can download and install from here


Once the tool is installed ,create a simple c file

Use the emcc compiler now

emcc hello.c -s WASM=1 -o hello.html

This will generate the html file as well as a wasm file and a js file

Run the html file as shown below

We can see the output in the browser

Next we create a c program with our defined function and invoke it via the javascript in the browser

Here we have defined a test function which we will invoke via the javascript once we have the wasm generated.

Again generate the wasm,js and the html file

Now in the hello1.html generated file we need to make small modifications to invoke the function

Add a button above the script section

And the actual button click event listener code before the script section ends. Here we can see we invoke the c function test.

On opening in browser and clicking button we see

So we can see we were able to render the output of the c function into the browser

Similarly to C , we can create wasm bindings for Rust,golang. In next blog we take a look at a Rust program and compile it to wasm and execute it in a browser.

For more details one can follow the mozilla website (https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm)