.NET - Wasmtime

## Keyboard shortcuts

Press `←` or `→` to navigate between chapters

Press `S` or `/` to search in the book

Press `?` to show this help

Press `Esc` to hide this help

# Using WebAssembly from .NET

The Wasmtime NuGet package can be used to programmatically interact with WebAssembly modules.

This guide will go over adding Wasmtime to your project and demonstrate a simple example of using a WebAssembly module from C#.

Make sure you have a .NET Core SDK 3.0 SDK or later installed before we get started!

## Getting started and simple example

Start by creating a new .NET Core console project:

    $ mkdir gcd
    $ cd gcd
    $ dotnet new console

Next, add a reference to the Wasmtime NuGet package to your project:

    $ dotnet add package --version 0.19.0-preview1 wasmtime

Copy this example WebAssembly text module into your project directory as `gcd.wat`.

    (module
      (func $gcd (param i32 i32) (result i32)
        (local i32)
        block  ;; label = @1
          block  ;; label = @2
            local.get 0
            br_if 0 (;@2;)
            local.get 1
            local.set 2
            br 1 (;@1;)
          end
          loop  ;; label = @2
            local.get 1
            local.get 0
            local.tee 2
            i32.rem_u
            local.set 0
            local.get 2
            local.set 1
            local.get 0
            br_if 0 (;@2;)
          end
        end
        local.get 2
      )
      (export "gcd" (func $gcd))
    )

This module exports a function for calculating the greatest common denominator of two numbers.

Replace the code in `Program.cs` with the following:

    using System;
    using Wasmtime;

    namespace Tutorial
    {
        class Program
        {
            static void Main(string[] args)
            {
                using var engine = new Engine();
                using var module = Module.FromTextFile(engine, "gcd.wat");

                using var host = new Host(engine);
                using dynamic instance = host.Instantiate(module);

                Console.WriteLine($"gcd(27, 6) = {instance.gcd(27, 6)}");
            }
        }
    }

Run the .NET core program:

    $ dotnet run

The program should output:

    gcd(27, 6) = 3

If this is the output you see, congrats! You've successfully ran your first WebAssembly code in .NET!

## More examples and contributing

The .NET embedding of Wasmtime repository contains the source code for the Wasmtime NuGet package.

The repository also has more examples as well.

Feel free to browse those, but if you find anything missing don't hesitate to open an issue and let us know if you have any questions!