Skip to content

huoshan12345/MixedIL.Fody

Repository files navigation

MixedIL.Fody

Build NuGet package .net License
Icon

This is an add-in for Fody which allows you to impliment C# method by IL code.


Installation

  • Include the Fody and MixedIL.Fody NuGet packages with a PrivateAssets="all" attribute on their <PackageReference /> items. Installing Fody 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.


Usage

  1. Write a method stub in a C# project with keyword extern and an attribute provided in MixedIL called MixedILAttribute
using MixedIL;

namespace System;

public class ObjectHelper
{
    [MixedIL]
    public static extern bool AreSame<T>(ref T a, ref T b);
}
  1. 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
    }
}
  1. Compile the project and that's it.

NOTE:

  • 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

Options that can be configured through some MSBuild properties to set in consuming projects.

  • MixedILExcludeIgnoresAccessChecksToAttribute: Exclude IgnoresAccessChecksToAttribute from source files to comiple.

NOTE:

  • IgnoresAccessChecksToAttribute is used to access non-public types and members across assemblies through IL code. It is helpful when you are using MixedIL or System.Reflection.Emit.

Examples


Comparison with InlineIL.Fody

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 using InlineIL.