Wasm Builders 🧱

Deepanshu Arora
Deepanshu Arora

Posted on

.NET(DotNet) and WebAssembly Rundown with Fibonacci

With the Recent Release of Wasi.Sdk which is an experimental package that can build .NET Core Applications into Standalone WASI-Compliant(.wasm) files.

Here is a quick rundown of a demonstration that will help you get started with Wasi.Sdk

Important Note:
You must download and install this preview version of .NET 7.0.0-preview.2 in order to get this demo working. With other versions of .NET, this demo will not compile and hence you will not be able to run it.

Step 1
First we will have to create a new .NET Console Application and we can create one using the following command:

dotnet new console -o MyFirstWasiApp

You can name your Console Application as per your requirements in my case, I have named it MyFirstWasiApp

Note that by default, the canonical example that is being used when you build the Console Application in Step 1, is a Hello World Example that will return Hello World as a result to the Console.

Since we want to run a Fibonacci Example here, you can replace the existing code that is present in the Program.cs file with the following code snippet:

using System;

namespace MyFirstWasiApp
{
    public class Program
    {

        public void fibonacci(ref int num){
            int a=1,b=0,temp;
            while(num >= 0){
                temp=a;
                a=a+b;
                b=temp;
                num--;
            }
            Console.WriteLine("Fibonacci Term is: "+b);
        }


        public static void Main(string[] args)
        {
            Program p = new Program();
            int num=10;
            p.fibonacci(ref num);
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Also Note that the With the current State of the Experimental WASI SDK it does not allow to take user input through the Console through the ReadLine() method.

Step 2
Navigate to the newly created Console Application Directory:

cd MyFirstWasiApp

Step 3
Now, in this third step, we will have to import the Wasi.Sdk package to our Console Application in so that our WASM Binary can have support for WASI Bindings.

dotnet add package Wasi.Sdk --prerelease

Step 4
Finally, you can build your application now using the following command:

dotnet build

Now, you will be able to see your Output WebAssembly Binary that this produces in the following Directory: bin/Debug/net7.0/MyFirstWasiApp.wasm.

Now, you can run it on Wasmtime Runtime Environment by executing:

wasmtime run MyFirstWasiApp.wasm

Oldest comments (0)