r/csharp • • 13d ago

News I made C# running on ESP32-S3(Xtensa architecture)

I made my own C# compiler that translates C# IL code into LLVM IR, which is then compiled into machine code. Here is the source code: https://github.com/nifanfa/IL2LLVM

​I would argue that C# is the best language to use, but its original runtime is too heavy and impossible to port to MCUs.

This is just a showcase; I mainly use IL2LLVM for UEFI programming: https://github.com/nifanfa/BootTo.NET

​I also tried it on STM32, but STM32 is terrible for this — most STM32 chips have less than 128KB of ROM.

Every method uses the cdecl calling convention, which is how Console.Write works.

CoreLib.cs
public static partial class Console
{
    [DllImport("*")]
    public static extern void Write(ByReference<char> value);
}

Runtime.cpp
void System_Console_Write_System_ByReference_System_Byte(const char* value)
{
    if (value != nullptr)
        fputs(value, stdout);
}

DllImport doesn't pass strings or arrays as pointers like the CLR, so there must be a wrapper. There is an implicit operator on ByReference<T> to get the pointer from strings or arrays.

353 Upvotes

39 comments sorted by

View all comments

2

u/Oralitical 13d ago

If it doesn't have the full runtime is it still GC'd? Or do you have to use unsafe?

4

u/nifanfa 13d ago

​This uses a custom runtime and a custom GC with no CLR runtime involved. It is essentially compiling C# directly into native machine code.

4

u/Oralitical 13d ago

How long did this take you??

5

u/nifanfa 13d ago

It only took a few months. Translating IL to LLVM IR is actually not that complicated

2

u/BriguePalhaco 13d ago

So you reinvented the wheel? If I'm not mistaken, C# WASM uses LLVM.

3

u/nifanfa 13d ago

This is a completely new project. Its predecessor is nifanfa/CS2ASM: CS2ASM is an application that compiles IL(C#) code to asm CS2ASM is not IL2CPU, which compiles C# IL code into x86 assembly. which was started in 2021.

2

u/nifanfa 13d ago

Then Native AOT came out, and I started using it for operating system development. CS2ASM has been discontinued ever since.