CSharpScripting

Chuck Smith edited this page 2026-11-25 01:11:12 +00:00 · 1 commit

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

C# game scripting: the CoreCLR experiment (issue #47)

Status: experiment done on Linux (2026-11-18, branch core_clr), waiting for the user's decision (section 6). Not meant to be fully functional (user): it answers #47's questions and shows how C# would fit #41's reflection. Code: Prototypes/CSharpScripting/ (opt-in -DPRIMAL_CSHARP_PROTO=ON, CMake only, needs the .NET 10 SDK).

cmake --preset linux-release -DPRIMAL_CSHARP_PROTO=ON
cmake --build --preset linux-release --target CSharpScripting
x64/Release/CSharpScripting [entity count]      # all checks + measurements; exit code 0 when all pass

1. What was built

  • The host (ManagedHost.cpp, about 150 lines):
    • nethost (linked statically from the SDK's app host pack) finds hostfxr;
    • hostfxr starts CoreCLR from Primal.Scripting.runtimeconfig.json;
    • hdt_load_assembly loads Primal.Scripting.dll into the default AssemblyLoadContext;
    • hdt_get_function_pointer returns its [UnmanagedCallersOnly] Bootstrap();
    • Bootstrap exchanges two tables of function pointers (ManagedApi.h ↔ Interop.cs). Every call after that is a plain function pointer both ways: no delegates, no marshalling, UTF-8 strings.
  • Primal.Scripting (C#, about 760 lines), the engine's half:
    • EntityScript and GameScript with BeginPlay/Update/EndPlay, the C++ lifetime;
    • [Property(Min, Max, Tooltip)] and [ScriptName];
    • Entity;
    • ScriptHost: the game assembly in a collectible AssemblyLoadContext, registration, GCHandles, field get/set as text, hot reload.
  • GameScripts (C#), a game's assembly: FanScript (the sample of Docs/Reflection.md), SpinScript, GarbageScript, and the game script ScoreKeeper.
  • The bridge (ManagedScripts.cpp):
    • A C# entity script is a ManagedEntityScript on the C++ side: an ordinary EntityScript that the frame phases create, begin, update and end, and that forwards each call to its C# object.
    • C# game scripts run through one C++ game script.
    • C# types register in #41's reflection registry and the engine's script registry, under the same FNV-1a name hashes as C++ types, so game.bin, the editor and game_entity::create() can't tell them apart.
    • The reflection runtime got one addition for this: type-level read_field/write_field, because a C# object has no fixed field addresses (the GC moves it).

2. Results (Release, clang 23, Ryzen 9 5900X, .NET 10.0.14 on CachyOS)

All checks pass on clang and GCC (Debug and Release):

  • FanScript registered from C#, with hash c1dba0e2…, the same as C++'s;
  • 4 fields with their types and metadata;
  • found by find_script_creator("FanScript");
  • created by game_entity::create();
  • begin_play() at the sync point and update() moving the entity;
  • read_text()/write_text() round trip through C#;
  • ScoreKeeper started at the first frame and ended by end_game_scripts();
  • hot reload with the old code unloaded.
Runtime start (hostfxr → Bootstrap) 30–35 ms, once per process
Game assembly load + registration (3–4 types) 16 ms
One call C++ → C# / C# → C++ 6.5 ns / 5.6 ns
Calls from all 24 job system threads at once 9.6 M calls in 5.1 ms: native threads attach by themselves
Hot reload of 100 scripts (save fields, unload, load, restore) 9 ms; the old AssemblyLoadContext is really gone (WeakReference check)

Frame time with 10,000 scripts, ms (median / p99), 200 frames:

moves its entity (set_position) math only (no engine call)
C++ script 16.4 / 18.2 0.092 / 0.115
C# script, one call per script 16.7 / 18.3 0.171 / 0.261
C# scripts, one call per frame for all 16.5 / 19.0 0.138 / 0.175
  • The C# cost is about 8 ns per script per frame (one call each way, plus the virtual call in C#), 4–5 ns when the engine calls all C# scripts at once. At 10,000 scripts that is 0.05–0.08 ms per frame.
  • The left column is the engine's, not C#'s: script::EntityScript::set_position() searches the per-thread transform cache linearly (Script.cpp, USE_TRANSFORM_CACHE_MAP 0), so N scripts that move their entity cost O(N²) per frame: 16–21 ms at 10,000, 0.27 ms at 1,000, in C++ and C# alike. Filed as #57; it goes away when scripts write ECS components directly (#52 step 2).

Garbage collection:

  • Scripts that don't allocate cause no collections at all (every row above: 0).
  • 10,000 scripts that allocate a list and a string each frame (1.8 MB per frame) cause a gen-0 collection every ~9 frames, ~0.75 ms each. The median frame is 1.65 ms; p99 is 5.6 ms, and max 7.2 ms.
  • So allocation-free gameplay code (pooled lists, no LINQ or string formatting per frame, structs) is a rule C# scripts must follow, as in Unity. A Roslyn analyzer could flag allocations in Update().

3. Findings

  • hdt_load_assembly (.NET 8+) is required, not the classic hdt_load_assembly_and_get_function_pointer. The classic call loads each assembly into an isolated context of its own. Game assemblies would then see a second copy of EntityScript, and their scripts wouldn't be EntityScripts.
  • Game assemblies load from bytes (LoadFromStream), so the file stays unlocked and can be rebuilt while the engine runs (it matters on Windows). Primal.Scripting resolves from the default context: the game context's Load() returns null for it.
  • What survives a hot reload: only [Property] fields, through the same text serializer game.bin would use.
    • Private state starts over, and game scripts restart.
    • A real version needs either a hook (OnReload) or "all fields of a script are saved on reload" (Unity's model).
    • Native ids (entities) survive: the C++ ManagedEntityScript stays, only its C# object is replaced.
  • Exceptions must not cross into C++ (the engine has none on MSVC). Every entry point catches and logs; an exception in one script's Update() logs an error and the frame goes on.
  • Threading: calls work from every job system thread without setup. Scripts run serially today (Script.cpp), so parallel C# scripts are as open as parallel C++ scripts (#1).
  • The editor is a .NET 10 process itself (PrimalEditor.csproj: net10.0-windows). There, game assemblies could load into the editor's own runtime (a collectible context per game, which is simpler than today's game DLL reload); EngineDLL would get the function tables from the editor instead of starting a runtime. Not tested.
  • The runtime can't be unloaded from a process (a .NET limit); only game assemblies come and go. Startup is 30 ms.
  • Arch packages the native host pack as arch-x64, not linux-x64; the CMake file searches for any runtime identifier.

Not done (out of the experiment's scope):

  • Windows. The hosting code has the wchar_t paths and LoadLibraryW, but it hasn't been built there (plan doc A38: the VM needs the .NET SDK).
  • Shipping: NativeAOT, or a bundled runtime of about 70 MB.
  • Debugging both languages at once.
  • C# access to ECS components.
  • C# scripts in the editor.

4. What C# changes for #41

  • C# scripts need neither macros nor a generator: [Property] plus .NET reflection gives the same tables.

  • C# needs bindings to C++ types: ECS components (Position, the game's own components), the entity API, later assets. That is a description of C++ structs in C#, and option 2's generator already reads those headers: it can write the C# structs (same layout, [StructLayout(Sequential)]) and the accessors next to the C++ registration. Hand-written bindings are the alternative, and drift.

  • So #47 doesn't change #41's recommendation, it strengthens it:

    • without C#, the generator is the in-class macro the user wants (the user leans to it for C++ classes, 2026-11-18);
    • with C#, it also produces the bindings.

    #41's option can be decided now, independently of #47.

5. Costs if C# is adopted

  1. Hosting in the engine: the experiment's host and bridge, moved into the engine (an Engine/Scripting/ or EngineDLL part), with the function tables as the ABI. About a week.
  2. Bindings: the components, the entity API, input, logging. Generated from #41's generator. Grows with the API.
  3. The game project: a .csproj next to (or instead of) the .vcxproj, built by the editor (dotnet build), and the editor's script templates.
  4. Shipping:
    • CoreCLR next to the game (about 70 MB, hot reload possible);
    • or NativeAOT (the C# compiled to a native library; no JIT, no hot reload, needed for consoles).
    • Decide when shipping matters (#33).
  5. Debugging: C# with Rider/VS Code/Visual Studio attached to the engine process, C++ with gdb/lldb/Visual Studio. Visual Studio debugs both at once on Windows; on Linux it's two debuggers.
  6. Rules for game code: no allocation per frame, no exceptions across frames, EndPlay() instead of finalizers.

6. Decisions for the user

  1. C# scripting:

    • (a) adopt it as the gameplay language next to C++ (the Flax/Unity model: the engine and performance-critical code in C++, game logic in C#);
    • (b) keep C++ only, and leave the experiment as the reference;
    • (c) decide later. #13 (the Avalonia editor) is the last point: it would host the scripts.

    The measurements show no technical blocker: interop costs nanoseconds, hot reload works, and GC is a discipline, not a wall.

  2. If (a): when. Recommended: after #52 step 4, the game API that the bindings expose, together with #41's generator writing them.

  3. #41's option (Docs/Reflection.md section 7) can be decided now: option 2 serves both answers.

7. The user's direction and follow-up questions (2026-11-18)

Direction, if C# is adopted: C# is the only language of the user's (game designer's) side; C++ stays for the engine itself. So game projects would have no C++ scripts or game DLL, and #41's C++ reflection would cover the engine's own types (components, engine-provided scripts) and generate the C# bindings.

Would generated bindings be faster?

  • Not by being generated. Generated and hand-written bindings compile to the same calls.
  • Speed comes from the binding's design, and generation is what makes the fast design practical:
    • Each call into C++ costs about 6 ns. A C# struct with the component's exact layout costs about 1 ns: C# reads and writes the component in its ECS chunk through a ref (ref Position p = ref entity.Get<Position>()).
    • C# systems can loop over a chunk as a Span<Position>, with no call per entity.
    • Both need C# structs that match the C++ layout exactly, which a generator keeps in step (#41 option 2) and hand work doesn't.
  • The experiment's per-script cost (about 8 ns) is the call into each script. "One call for all" cuts it about in half, and the engine's own set_position() (#57) costs 100 times more.

Would hosting inside the engine be faster?

  • No. The experiment already runs in the engine's process, and every call is a function pointer both ways: moving the host is structure, not speed.
  • The one gain is in the editor: it's a .NET 10 process, so scripts can load into its runtime instead of starting a second one.

Hot reload in development, NativeAOT when shipping: a problem?

  • No, with two conditions.
    1. Registration and field access must not use runtime reflection. The experiment uses GetTypes(), GetCustomAttribute(), FieldInfo.SetValue() and Expression.Compile(). NativeAOT trims what it can't see, and runs compiled expressions interpreted, so reflection would need annotations and would be slow there.
      • A Roslyn source generator writes the registration and typed field accessors at compile time, the same code under JIT and AOT, and faster than reflection in both.
      • It's the C# counterpart of #41's C++ generator.
    2. The C++ side mustn't care which one runs. The function-table ABI already allows this:
      • in development, the host gets Bootstrap through hostfxr, and game assemblies load into a collectible context (hot reload);
      • in a shipped game, Primal.Scripting and the game's C# are compiled with NativeAOT into one native library that exports Bootstrap ([UnmanagedCallersOnly(EntryPoint = "primal_bootstrap")]), and the host gets it with dlsym/GetProcAddress.
      • Same tables, same calls.
  • Costs to plan for:
    • NativeAOT builds on the target OS (Windows on Windows, Linux on Linux): CI has both runners;
    • an AOT build in CI, so that what only fails under AOT is caught early;
    • no Assembly.Load in a shipped game (all the game's C# is compiled in);
    • consoles through their vendors' NativeAOT support.
  • Alternative for development: .NET's own hot reload (metadata updates, as dotnet watch does) keeps object state across edits, but needs a debugger or DOTNET_MODIFIABLE_ASSEMBLIES=debug, and not every edit is allowed. The collectible context always works but keeps only [Property] state. Both could coexist.

Null checks without Unity's trap:

  • Unity overloads == on UnityEngine.Object so that a destroyed object "equals null". But ?., ??, is null and pattern matching don't use the overload, so they disagree with ==, and nullable analysis can't help.
  • The rule here: null means only a real null reference; being alive is a separate, explicit property.
  • Entities are a value type (Entity, a generation-checked id, as in the experiment).
    • entity.IsAlive checks the generation, so a destroyed entity's old handle is never mistaken for another.
    • A function that may find nothing returns Entity? (Nullable<Entity>), so ?. and ?? work with their real meaning: FindEntity("Boss")?.Position ?? Vector3.Zero.
  • Scripts are real objects that are never "fake null".
    • GetScript<T>() returns T?: a real null when the entity has none.
    • A removed script keeps existing as an object until nothing references it. script.IsAlive says whether it's still in play, and using the engine through a dead script or entity is caught: logged as an error in development (the call does nothing), and an exception in tests.
  • Components: Has<T>(), TryGet<T>(out T value) and ref T Get<T>(). No nullable component values.
  • Nullable reference types are on, with warnings as errors (the experiment's projects already do this), so the compiler checks nulls. This is the safety Unity's overload rules out.

How Unity does it (for comparison; from general knowledge, not checked against Unity's current docs):

  • Compiler: Roslyn compiles game C#. Roslyn analyzers and source generators are supported; DOTS/Entities uses source generators, and some packages also rewrite the compiled IL (IL post-processing).
  • Editor: runs on Mono's JIT. A script change reloads the whole scripting domain, which is Unity's slow "domain reload"; there is no state-keeping hot reload.
  • Shipping: IL2CPP, which translates the IL to C++ and compiles that with the platform's compiler: AOT, like NativeAOT.
  • What it does for frame times:
    • The Burst compiler (LLVM) compiles a restricted C# subset ("HPC#": structs, no managed objects, no GC) for jobs to SIMD machine code. That's where Unity's performance guarantees come from, not from its general C#.
    • The Boehm GC can run incrementally, to spread pauses.
    • The rest is the "don't allocate in Update()" discipline.
  • Runtime: Unity has announced a move to CoreCLR, which is still in progress.

The user wants a more robust scripting style than Unity's, closer to Unreal's (2026-11-18): reflection specifiers, components on entities, tick groups and order, events, subsystems, references that are real nulls. A design proposal for that C# API is the next step if C# is adopted.

Pages 19

View all

Clone this repository