This is an add-in for Fody which allows you to impliment C# method by IL code.
-
Include the
Fody
andMixedIL.Fody
NuGet packages with aPrivateAssets="all"
attribute on their<PackageReference />
items. InstallingFody
explicitly is needed to enable weaving.<PackageReference Include="Fody" Version="..." PrivateAssets="all" /> <PackageReference Include="MixedIL.Fody" Version="..." PrivateAssets="all" />
-
If you already have a
FodyWeavers.xml
file in the root directory of your project, add the<MixedIL />
tag there. This file will be created on the first build if it doesn't exist:<?xml version="1.0" encoding="utf-8" ?> <Weavers> <MixedIL /> </Weavers>
See Fody usage for general guidelines, and Fody Configuration for additional options.
- Write a method stub in a C# project with keyword
extern
and an attribute provided inMixedIL
calledMixedILAttribute
using MixedIL;
namespace System;
public class ObjectHelper
{
[MixedIL]
public static extern bool AreSame<T>(ref T a, ref T b);
}
- Then create a .il file in the the C# project and implement the method in il code. C# dll
.class public abstract auto ansi sealed beforefieldinit System.ObjectHelper
{
.method public hidebysig static bool AreSame<T>(!!T& a, !!T& b) cil managed aggressiveinlining
{
.maxstack 2
ldarg.0
ldarg.1
ceq
ret
}
}
- Compile the project and that's it.
- The method signature and declaring type should be the same.
- Only il method body will be injected into the assembly file, other parts like attributes in il code won't. You can just write all the other parts using C# code.
Options that can be configured through some MSBuild properties to set in consuming projects.
MixedILExcludeIgnoresAccessChecksToAttribute
: Exclude IgnoresAccessChecksToAttribute from source files to comiple.
- IgnoresAccessChecksToAttribute is used to access non-public types and members across assemblies through IL code. It is helpful when you are using
MixedIL
orSystem.Reflection.Emit
.
- An example project
- A reimplementation of the
System.Runtime.CompilerServices.Unsafe
called MixedIL.Unsafe is provided as an example.
InlineIL.Fody is a remarkable fody add-in which lets you inject IL instructions by calling normal static C# methods. While there are some differences, so you can choose based on your requirement.
- Basically, in most cases you can use
InlineIL
, which is more friendly to C# developers. MixedIL
is more flexible and less restrictive, since pure IL code will be written.
For instance, you can invoke backing field of a property without setter by pure IL, like this:
stfld string [System.Runtime]System.Reflection.AssemblyKeyNameAttribute::'<KeyName>k__BackingField'
see example code.
However, up to now, you will get compile error if you would like to implement it usingInlineIL
.