C#
Write a Basalt plugin in C# with NativeAOT-LLVM: familiar .NET code in a module of about 950 KB, built on Linux x64.
Choose C# when .NET is the language you work in and you can build on Linux x64. Plugins are ordinary C# classes with delegates as handlers and nullable values for answers that may be missing. It is the heaviest option to set up and run: the compiler is the experimental NativeAOT-LLVM for WebAssembly, the module carries the .NET runtime and its garbage collector (about 950 KB for a small plugin), the first build downloads about 400 MB, and the module needs about 51 MB of memory as soon as it starts. Speed has not been measured the way C was, and a garbage-collected runtime will not match C, C++, Zig or Rust for a plugin that runs often.
Memory limit and platform
A C# module needs about 51 MB of memory when it starts, and the default memory-mb under [plugins] is 32. Raise it, for
example to 64, in the server settings, or the plugin does not start. Kiln builds C# only on
Linux x64.
What Kiln installs#
Nothing by hand. Kiln downloads the .NET 10 SDK, the NativeAOT-LLVM compiler packages and the WASI SDK on the first build (about 243, 44 and 114 MB, 1.1 GB unpacked), into a per-user cache. It does not use a .NET SDK from your machine. On any platform other than Linux x64 the build stops with a message saying so. See Kiln.
Project layout#
kiln new greeter --lang csharpgreeter/
plugin.toml
.gitignore
resources/config.toml
resources/lang/en_us.toml
src/Main.csEvery .cs file under src/ is compiled together. There is no project file to write: Kiln generates one, with implicit
usings and nullable reference types off, so each file lists its own using lines. The module is written to
build/plugin.wasm; build/.kiln/ holds the SDK copy and scratch files and is rebuilt each time.
The entry point#
Write a public static class Plugin with a public static void Init(), inside a namespace. Kiln finds the class by the
text class Plugin in your sources, takes the namespace from that file, and generates the exports the server needs and a
call to Plugin.Init(). Init runs once, after the module loads; that is where you register listeners, commands and
tasks.
A first plugin#
This plugin greets a player when they join and adds a /greeter hello [times] command. It is the whole of src/Main.cs.
using Basalt.Server.Commands;
using Basalt.Server.Core;
using Basalt.Server.Events;
using Basalt.Server.Log;
using Basalt.Server.Players;
namespace Greeter;
public static class Plugin
{
static void OnJoin(int ctx)
{
int player = EventBus.EventPlayer(ctx);
if (player == 0)
{
return;
}
string name = Directory.PlayerName(player) ?? "player";
Directory.Send(player, "<green>Welcome, {name}!", new Args().Add("name", name));
}
static void Hello(int ctx)
{
long times = Arguments.I64(ctx, "times") ?? 1;
for (long i = 0; i < times; i++)
{
Sender.Reply(ctx, "<yellow>Hello from greeter!");
}
}
public static void Init()
{
Logger.LogInfo("greeter loaded");
EventBus.On("player.join", Priority.Normal, OnJoin);
Registry.Register("greeter hello [times: int 1..5]", "", Hello);
}
}EventBus.On listens to an event, see Events; Registry.Register registers a command from a
spec such as greeter hello [times: int 1..5], see Commands. The text is
MiniMessage, and {name} is filled from the arguments.
How the SDK names things#
Pages in this section write calls in the C++ form (players::send); the C# spelling is in The SDK.
-
Where things live: a namespace per area,
Basalt.Server.<Area>, holding one static class named for its job, not for the area. Methods are the C++ name in PascalCase. The classes are:Area Namespace and class coreBasalt.Server.Core:Args,Priority,Level,HandlerlogBasalt.Server.Log.LoggerconfigBasalt.Server.Config.SettingstextBasalt.Server.Text.TranslationsplayersBasalt.Server.Players.DirectorydataBasalt.Server.Data.PlayerStoreeventsBasalt.Server.Events.EventBuscommandsBasalt.Server.Commands:Registry(register),Arguments(read arguments),Sender(reply, name, console)tasksBasalt.Server.Tasks.SchedulermenusBasalt.Server.Menus.InventoryMenuworldsBasalt.Server.Worlds.WorldManagerentitiesBasalt.Server.Entities.EntityManageritemsBasalt.Server.Items.CataloghudBasalt.Server.Hud.DisplayspacketsBasalt.Server.Packets.InterceptorserverBasalt.Server.Services.RuntimeServicesvaluesBasalt.Server.Values:ValueWriter,Value,ValueIterSo
players::sendisDirectory.Send,players::player_nameisDirectory.PlayerName,commands::command_replyisSender.Replyandconfig::config_i64isSettings.ConfigI64. -
Strings in are
string. -
Strings out are
string,nullwhen the call failed. A number that may be absent islong?. -
Optional arguments are default parameters:
Sender.Reply(ctx, text)andSender.Reply(ctx, text, args). -
Handles are plain
int.0is never a valid handle.Directory.PlayersOnline()returns anint[]. -
Argsisnew Args().Add(key, value), which returns theArgsso pairs chain. -
Constants are
Priority.LowesttoPriority.HighestandLevel.DebugtoLevel.Error. -
Handlers are the delegate
Handler,void (int ctx): a method group such asOnJoin, or a lambda (ctx => { ... }), which can capture variables.
Working with values#
Structured data is a value, see Values. new ValueWriter() builds a document, its methods
chain and Finish() returns a byte[], or null if the writer failed. A call that returns a value gives you a status and
an out Value to read. This keeps a count of joins in a JSON document (it needs the storage
capability, see
Configuration and storage):
using Basalt.Server.Services;
using Basalt.Server.Values;
static void RecordJoin(string who)
{
long total = 0;
if (RuntimeServices.DataRead("joins", out Value doc) == 0 && doc.TryFind("total", out Value found))
{
found.TryInt(out total);
}
byte[] document = new ValueWriter()
.BeginMap()
.Key("total").Int(total + 1)
.Key("last").String(who)
.End()
.Finish();
RuntimeServices.DataWrite("joins", document);
}The writer has Null, Bool, Int, Float, String, Bytes, BeginList, BeginMap, End and Key. For reading,
TryFind (a map), TryAt (a list), Count and Iter() walk a document, and TryInt, TryFloat, TryBool,
TryString and TryBytes return false when the value has another kind. Find and At return an absent Value instead
of failing, which answers every getter with false. The status of a failed call is one of the
result codes.
Building#
kiln buildgenerates a project for the NativeAOT-LLVM compiler, publishes it for wasi-wasm, writes build/plugin.wasm and checks
it. The plugin above is about 940 KB and takes 5 to 7 seconds to build once the toolchain is in place. kiln pack writes
build/greeter-0.1.0.bspkg for the server's plugins/ folder, see Kiln.
Proxy plugins#
The same language writes proxy plugins: kiln new <id> --lang csharp --target proxy, with Basalt.Proxy.<Area> in place of
Basalt.Server.<Area> (Basalt.Proxy.Events). Proxy plugins are packed as .bppkg, see
Proxy plugins.
Things to know#
- The module needs about 51 MB of memory at start. The .NET runtime sets up its heap when the module starts, so a plugin begins
above the default plugin memory limit of 32 MB and needs
memory-mb = 64or more, see the warning at the top. - The runtime is part of the module. About 940 KB of it is .NET and its garbage collector, so size and start-up are fixed costs. The collector frees what you drop, so allocating in a callback does not leak, but it adds work to handlers that run often.
- Keep exceptions out of callbacks. Exceptions are emulated in this build, so check values and return early instead of throwing.
- No
Console.Console.WriteLineand anything that touches files or the operating system pull in calls the server does not provide, and Kiln's check fails the build. Write to the server log withLogger.LogInfo. - Invariant culture. Globalization is in invariant mode, so formatting and comparison behave the same everywhere and no culture data is shipped.
- An experimental compiler. Keep plugin code to plain C#: classes, collections, strings and math. Library features that depend on the operating system, on threads or on reflection are best avoided.
Where to go next#
| The SDK | How calls, handles and errors work in every language |
| Values | The structured data format in full |
| Kiln | Creating, building and packing |
| Performance | Measured numbers and how to keep a tick short |
The same greeter, a leaderboard and a shop are a full example in the
ServerPlugin-Example repository, on the branch csharp.