WebAssembly - Convert WAT to WASM


In the previous chapter, we have seen how to write code in .wat i.e., WebAssembly text format. The WebAssembly text format will not directly work inside the browser and you need to convert it into binary format i.e., WASM to work inside browser.

WAT to WASM

Let us convert .WAT to .WASM.

The code we are going to use is as follows −

(module 
   (func $add (param $a i32) (param $b i32) (result i32) 
      get_local $a 
      get_local $b 
      i32.add
   ) 
   (export "add" (func $add)) 
)

Now, go to WebAssembly Studio, which is available at https://webassembly.studio/.

You should see something like this, when you hit the link −

Convert WAT to WASM

Click on Empty Wat project and click on Create button at the bottom.

Empty Wat Project

It will take you to an empty project as shown below −

Empty Project

Click on main.wat and replace the existing code with yours and click on the save button.

Existing Code

Once saved, click on the build to convert to .wasm −

Convert to WASM

If the build is successful you should see .wasm file created as shown below −

WASM File

Down the main.wasm file and use it inside your .html file to see the output as shown below.

For Example − add.html

<!doctype html>
<html>
   <head>
      <meta charset="utf-8">
      <title>WebAssembly Add Function</title>
   </head>
   <body>
      <script> 
         let sum; 
         fetch("main.wasm")
            .then(bytes => bytes.arrayBuffer()) 
            .then(mod => WebAssembly.compile(mod)) .then(module => {
            
            return new WebAssembly.Instance(module) 
         })
         .then(instance => {
            sum = instance.exports.add(10,40); 
            console.log("The sum of 10 and 40 = " +sum); 
         }); 
      </script>
   </body>
</html>

The function add is exported as shown in the code. The params passed are 2 integer values 10 and 40 and it returns the sum of it.

Output

The output is displayed in the browser.

Displayed
Advertisements