Skip to content

Instantly share code, notes, and snippets.

@paulirwin
Last active January 12, 2024 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulirwin/8465f3fd876d890174a2f72136668355 to your computer and use it in GitHub Desktop.
Save paulirwin/8465f3fd876d890174a2f72136668355 to your computer and use it in GitHub Desktop.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net8.0;net7.0;net6.0;net5.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.5" />
</ItemGroup>
</Project>
using Mono.Cecil;
using Mono.Cecil.Cil;
Directory.CreateDirectory("output");
const string dotnetVersion =
#if NET8_0
"8";
#elif NET7_0
"7";
#elif NET6_0
"6";
#elif NET5_0
"5";
#endif
var module = ModuleDefinition.CreateModule("Div", ModuleKind.Console);
var type = new TypeDefinition("", "Program", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed, module.TypeSystem.Object);
module.Types.Add(type);
var method = new MethodDefinition("Main", MethodAttributes.Public | MethodAttributes.Static, module.TypeSystem.Void);
type.Methods.Add(method);
var il = method.Body.GetILProcessor();
il.Emit(OpCodes.Ldc_R8, 1.0);
il.Emit(OpCodes.Ldc_R8, 0.0);
il.Emit(OpCodes.Div);
il.Emit(OpCodes.Conv_R8);
il.Emit(OpCodes.Conv_I8);
il.Emit(OpCodes.Call, module.ImportReference(typeof(Console).GetMethod("WriteLine", [typeof(long)])));
il.Emit(OpCodes.Ret);
module.EntryPoint = method;
module.Write("output/div.exe");
var runtimeConfigJson = $$"""
{
"runtimeOptions": {
"tfm": "net{{dotnetVersion}}.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "{{dotnetVersion}}.0.0"
}
}
}
""";
File.WriteAllText(Path.Join("output", "div.runtimeconfig.json"), runtimeConfigJson);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment