← 输入框|github.com|刷新
Skip to content

System.NullReferenceException for IL hooks in specific places #85

Open

Description

@Dual-Iron

Description

In specific cases, a System.NullReferenceException exception will be thrown from an ILHook's generated DMD (and sometimes FastDelegateInvokers.Invoke<...>) when using a custom delegate type for an instance method.

I got this to occur by doing the following:

  1. In an assembly A, IL hook an arbitrary method and call ILCursor.EmitDelegate<CustomDelegate>(someInstanceMethod)
  2. Call DetourModManager.Unload on A
  3. Load a new assembly, B, that shares the same name and version with A
  4. Hook the same method in the same way as A

This is when running Unity v4.6.3/Mono, targeting .NET Framework 3.5. Make sure that CustomDelegate is a delegate from your assembly, not e.g. Action or Func. Also make sure that someInstanceMethod is an instance method.

Example

delegate void A();

string Words = "Hi";

void PrintWords() {
    Console.WriteLine(Words);
}

void Enable() {
    IL.Room.Update += MyILHook;
}

void MyILHook(ILContext il) {
    ILCursor cursor = new(il);
    cursor.EmitDelegate<A>(PrintWords);

    // These also bug out because they compile as instance methods:
    // cursor.EmitDelegate<A>(() => Console.WriteLine(Words));
    // cursor.EmitDelegate<A>(() => Console.WriteLine("Hi"));
}

Before step 2, this runs fine. When Room.Update is called, Hi gets printed to the console.

After step 4, however, whenever Room.Update is called, you'll instead get a nasty exception:

System.NullReferenceException: Object reference not set to an instance of an object
at (wrapper dynamic-method) Room.DMD<Room..Update> (Room) <0x0008c>
etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions