bytecodealliance / componentize-dotnet

Tooling for creating WebAssembly components from C#
Apache License 2.0
19 stars 8 forks source link
csharp dotnet wasi wasm wasm-component

Latest Version

componentize-dotnet

Simplifying C# wasm components

A Bytecode Alliance hosted project

If you have any questions of problems feel free to reach out on the c# zulip chat.

Purpose

This is to simplify using Wasm components in c#.

Without this package, if you wanted to build a WASI 0.2 component with .NET, including using WIT imports/exports, there are several different tools you'd need to discover, download, configure, and manually chain together. Just figuring out which versions of each are compatible with the others is a big challenge. Working out how to get started would be very painful.

With this package, you can add one NuGet reference. The build output is fully AOT compiled and is known to work in recent versions of wasmtime and WAMR.

:construction: All the underlying technologies are under heavy development and are missing features. Please try to file it on the relevant underlying tool if relevant to that tool.

Getting started

Limitation: Although the resulting .wasm files can run on any OS, the compiler itself is currently limited to Windows.

1. Set up SDKs

If you don't already have it, install .NET 8+ SDK

2. Create a project and add BytecodeAlliance.Componentize.DotNet.Wasm.SDK package

Create a nuget.config file and add the dotnet-experimental package source for the NativeAOT-LLVM dependency:

    <add key="dotnet-experimental" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-experimental/nuget/v3/index.json" />
    <add key="nuget" value="https://api.nuget.org/v3/index.json" />

Add the componentize-dotnet package:

3. Configure the compilation output

Edit the .csproj file, adding the following inside the <PropertyGroup>:

    <RuntimeIdentifier>wasi-wasm</RuntimeIdentifier>
    <UseAppHost>false</UseAppHost>
    <PublishTrimmed>true</PublishTrimmed>
    <InvariantGlobalization>true</InvariantGlobalization>

Now you can dotnet build to produce a .wasm file using NativeAOT compilation.

4. Run the WebAssembly binary

If you have a recent version of wasmtime on your path, you can now run

wasmtime bin\Debug\net8.0\wasi-wasm\native\MyApp.wasm

(if needed, replace MyApp.wasm with the actual name of your project)

Creating a WASI 0.2 component, including WIT support

Lastest version of NativeAOT compiler package and the mono support in dotnet 9-preview 7 build native wasi 0.2 components with no additional tools.

Referencing a WIT file

The whole point of the WASI 0.2 component model is to be able to interoperate across components. This is achieved using WebAssembly Interface Type (WIT) files that specify data structures and functions to be imported or exported across components.

There is a full sample of this walk through creating WIT components for you reference in samples.

This package wraps wit-bindgen so that any .wit files in your project will automatically generate corresponding C# sources, allowing you to import or export functionality.

For example, add a file called calculator.wit into your project, containing the following:

package example:calculator;

interface operations {
  add: func(left: s32, right: s32) -> s32;
}

world computer {
  export operations;
}

world hostapp {
  import operations;
}

Before you can build, you'll now need to specify which world you're generating code for, i.e., choose whether you're importing or exporting functions.

Importing an implementation

One way to pick a world is by editing your .csproj, adding the following:

  <ItemGroup>
    <Wit Update="calculator.wit" World="hostapp" />
  </ItemGroup>

Another option, if you use Visual Studio, is to select the WIT file in Solution Explorer, and then look at the Properties pane:

image

You can simply type the world name hostapp into the properties pane.

Now you can call the imported Add function by putting the following in Program.cs:

using HostappWorld.wit.imports.example.calculator;

var left = 123;
var right = 456;
var result = OperationsInterop.Add(left, right);
Console.WriteLine($"{left} + {right} = {result}");

Since your component is no longer a self-contained application, you can no longer run it without also composing it with another WASI 0.2 component that implements the add function. To do that, either:

Exporting an implementation

If you're exporting functionality, you'll be building a class library, not an executable. So be sure to go to your .csproj and change <OutputType> from exe to library and delete any Program.cs.

Once you've done that, change your WIT file to use the computer world using one of the two techniques described above (i.e., either edit the .csproj or use the VS Properties pane).

Now when you build, you'll get an error like The name 'OperationsImpl' does not exist in the current context. This is because you've said you'll provide an implementation, but haven't yet done so. To fix this, add the following class to your project:

namespace ComputerWorld.wit.exports.example.calculator;

public class OperationsImpl : IOperations
{
    public static int Add(int left, int right)
    {
        return left + right;
    }

    public static string ToUpper(string input)
    {
        return input.ToUpperInvariant();
    }
}

Make sure to get the namespace exactly correct! Although this is quite difficult to figure out at the moment, hopefully a future version of the C# support in wit-bindgen will make it easier.

Now when you build, you'll get a real WASI 0.2 component that exports an implementation for this WIT definition. You can confirm it using wasm-tools by running:

wasm-tools component wit bin\Debug\net8.0\wasi-wasm\native\MyApp.wasm

Outputs:

package root:component;

world root {
  import ... various things ...

  export example:calculator/operations;
}

Composing components

Once you have a components containing the Adder and Calculator host, you can use wasm-tools to compose a runnable application:

wasm-tools compose -o composed.wasm MyApp.wasm -d AddImplementation.wasm

then run it:

wasmtime composed.wasm

While you can run wasm-tools manually, you can also generate this automatically. One way to do this is to create a new project and add the following:

 <Target Name="ComposeWasmComponent" AfterTargets="AfterBuild">
        <PropertyGroup>
            <EntrypointComponent>../CalculatorHost/bin/$(Configuration)/$(TargetFramework)/wasi-wasm/native/calculatorhost.wasm</EntrypointComponent>
            <DependencyComponent>../Adder/bin/$(Configuration)/$(TargetFramework)/wasi-wasm/native/adder.wasm</DependencyComponent>
        </PropertyGroup>

        <MakeDir Directories="dist" />
        <Exec Command="$(WasmToolsExe) compose -o dist/calculator.wasm $(EntrypointComponent) -d $(DependencyComponent)" />
    </Target>

Another option is to do it from the project where the final component will be composed as the output. See the example in the e2e tests

You can also use this technique to use other wasm-tools functionality such as wasm-tools strip to produce a final binary.

This final component can be used anywhere that WASI 0.2 components can be used. For example, use wasmtime as illustrated above.

Referencing Wit Packages

By default the project will find all wit files and execute wit-bindgen against each one. This is makes it easy to get started with a single wit file. If you have more complicated wit files, then you can create wit packages. To use folder with all the wit in it you can add the following to your .csproj.

<ItemGroup>
    <Wit Remove="**\*.wit"  />
    <Wit Include="wit-folder" World="wit-world" /> 
</ItemGroup>

Referencing Wit Packages from OCI Registries

Wit can be packaged into OCI Artifacts which can be pushed to OCI registries. To import a WIT definition from an OCI registry specify the Registry on the Wit Element. This will pull a WASM component binary that contains the WIT definition. wit-bindgen can use the binary format directly to generate the bindings. To view the WIT directly use wasm-tools component wit wit/wit.wasm.

  <ItemGroup>
    <Wit Remove="**\*.wit" />
    <Wit Include="wit/wit.wasm" World="command" Registry="ghcr.io/webassembly/wasi/cli:0.2.0" />
  </ItemGroup>

WIT strings and memory

The calculator example above works easily because it doesn't need to allocate memory dynamically. Once you start working with strings, you must add an extra line to the <PropertyGroup> in your host .csproj file (that is, the application that's importing the interface):

    <IlcExportUnmanagedEntrypoints>true</IlcExportUnmanagedEntrypoints>

(You don't need to add this to your class library/exporting .csproj.)

If you get a build error along the lines of _failed to encode a component from module ... module does not export a function named cabi_realloc_ then check you have remembered to add this line.

Troubleshooting

Imports Wrong Type

*import 'wasi:...' has the wrong type* 

You need a different version of Wasmtime. Currently this package targets Wasmtime. WASI 0.2 is now stable and so you shouldn't run into this often.

Component imports missing

Error: component imports instance `wasi:cli/environment@0.2.0`, but a matching implementation was not found in the linker

Caused by:
    0: instance export `get-environment` has the wrong type
    1: function implementation is missing

Some imports automatically imported since they are so common. In this case you should tell the runtime to implement those imports. For instance for the error above, in wasmtime you might add -S cli to the wasmtime serve command like wasmtime serve -S cli to include the wasi:cli/environment@0.2.0 in wasmtime runtime host implementation.

Credits

This project was original developed and forked from https://github.com/SteveSandersonMS/wasm-component-sdk under the Apache 2.0 License with a LLVM exception.

This is a wrapper around various other bits of tooling:

Contributing

See our contributing docs for details on how to build and contribute to this project.