📚 Blog post available here
- Install .NET 8 SDK (currently RC1 is the latest)
- Install the .NET 8 WASI workload
dotnet workload install wasi-experimental
- Download WASI SDK and extract. Then either
- add
WASI_SDK_PATH
environment variables pointing to the extracted directory or, - you will need to set
<WasiSdkRoot></WasiSdkRoot>
MSBuild variable in your WASI projects - pointing to the extracted directory
- add
- Install the preferred WASM runtime/CLI runner. The recommended one is wasmtime
- (optional) Download binaryen, extract and the extracted
bin
folder to thePATH
. This allows usingwasm-opt
Basic demo of .NET 8 console application compiled for wasm-wasi
. Steps to build:
cd src/WasiDemo
dotnet publish -c Release
Note that we run the publish
workflow instead of a normal build
, instead of a normal build because this is the only way to get trimming to kick in and reduce the size of the built app.
This can now be run:
wasmtime bin/Release/net8.0/wasi-wasm/AppBundle/WasiDemo.wasm
And it should print:
I'm alive in C#!
Alternatively, it's possible to further optimize the WASM file by first running wasm-opt
:
wasm-opt -Oz --enable-bulk-memory bin/Release/net8.0/wasi-wasm/AppBundle/WasiDemo.wasm -o bin/Release/net8.0/wasi-wasm/AppBundle/WasiDemoOpt.wasm
wasmtime bin/Release/net8.0/wasi-wasm/AppBundle/WasiDemoOpt.wasm
The result should be a smaller WASM file.
Example of surfacing a .NET method as a WASM function. Steps to build:
cd src/WasiExport
dotnet publish -c Release
Instead of going through the WASM entrypoint (the _start()
function, which points to Main()
in C#).
wasmtime bin/Release/net8.0/wasi-wasm/AppBundle/WasiExport.wasm --invoke hello
Note that a C# Main
method is still needed (even if empty) because it will boot the Mono runtime, and it will be internally called prior to our function execution.
However, this is needed only once - and is tracked by a static state - so if we load the produced WASM file into another process, and continuously call our function, Main
would only be called once on first invocation of our function.
The same optimizations as before can be done on this project too.