English 中文(简体)
WebAssembly - Convert WAT to WASM
  • 时间:2024-12-22

WebAssembly - Convert WAT to WASM


Previous Page Next Page  

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 pke this, when you hit the pnk −

Convert WAT to WASM

Cpck on Empty Wat project and cpck on Create button at the bottom.

Empty Wat Project

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

Empty Project

Cpck on main.wat and replace the existing code with yours and cpck on the save button.

Existing Code

Once saved, cpck 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