File: lang-dotnet.md

package info (click to toggle)
rust-wasmtime 26.0.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 48,504 kB
  • sloc: ansic: 4,003; sh: 561; javascript: 542; cpp: 254; asm: 175; ml: 96; makefile: 55
file content (87 lines) | stat: -rw-r--r-- 2,171 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# Using WebAssembly from .NET

The [Wasmtime](https://www.nuget.org/packages/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](https://dotnet.microsoft.com/download)
installed before we get started!

## Getting started and simple example

Start by creating a new .NET Core console project:

```text
$ mkdir gcd
$ cd gcd
$ dotnet new console
```

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


```text
$ dotnet add package --version 0.19.0-preview1 wasmtime
```

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

```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:

```c#
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:

```text
$ dotnet run
```

The program should output:

```text
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](https://github.com/bytecodealliance/wasmtime-dotnet)
contains the source code for the Wasmtime NuGet package.

The repository also has more [examples](https://github.com/bytecodealliance/wasmtime-dotnet/tree/main/examples)
as well.

Feel free to browse those, but if you find anything missing don't
hesitate to [open an issue](https://github.com/bytecodealliance/wasmtime-dotnet/issues/new) and let us
know if you have any questions!