How NativeAOT/CoreRT pass command line parameters into C# code.

Andrii Kurdiumov
2 min readFeb 5, 2021

--

Run for command line

If you want write applications for UEFI using C# that’s already possible, thank for examples from Michal Strehovský. Unfortunately UEFI does not supported by Microsoft as valid target, so development environment quite limited and experimental. Most important limitation is that you cannot use standard runtime library and BCL which defeat whole point of using C#. For now you have to maintain small library by borrowing code from NativeAOT/CoreRT project.

If you write your custom runtime you most of the time limited to start your application with void Main() entry point. That’s not a problem unless you want use C# 9.0 features and write all your application in script-like format. Unfortunately, by default, .NET generates entry point int Main(string[]) for you, and if you compile application using NativeAOT you will see following error message:

Unhandled Exception: System.Exception: Main() has parameters, but the class library doesn’t support them

This error produced because custom runtime lack of methods which would be used by NativeAOT compiler to produce entry point. Compiler produce approximately following code around __managed_Main function which represents entry point in the C# code.

Actual generated code slightly more involved, but you can take a look at it in the NativeAOT source code at StartupCodeMainMethod.cs to see what’s going on behind the scene.

So we have to supplant runtime library with at least following implementation

Once you add that code, your custom runtime library magically starts working.

In case of UEFI this is all what’s needed to be able write short programs without writing Main() class in simplified manner. You can write simply:

That’s much better for tutorials and short applications which utilise UEFI and NativeAOT :) Who knows maybe some C# unikernel finally arise

Example of this change can be seen at sample repo: https://github.com/kant2002/nativeaot-commandline

--

--

Andrii Kurdiumov
Andrii Kurdiumov

Written by Andrii Kurdiumov

Math lover, lost in the woods of software development

No responses yet