You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2.1 KiB

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.15.0-preview1 wasmtime

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

{{#include ../examples/gcd.wat}}

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 host = new Host();
            using var module = host.LoadModuleText("gcd.wat");

            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!