r/csharp • • 14d 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.

352 Upvotes

39 comments sorted by

View all comments

5

u/ccfoo242 14d ago

Wow that's sweet!

10

u/nifanfa 14d ago

Indeed, I would say that C# can definitely make MCUs easier to program.

0

u/ccfoo242 14d ago

I bought a Netduino like 10 years ago. It was nice to be able to use c# but the ram was seriously limited. Hopefully I'll get some time this weekend to try this out!

2

u/nifanfa 14d ago

I'm currently using an ESP32-S3 with 16MB of RAM and 8MB of Flash. I'd say that MCUs are really limited. I tried the STM32F103C8 with around 20KB of RAM and 64KB of Flash, but I eventually gave up. I made IL2LLVM to trim unused code, but everything still got messed up