Search code examples
c#dnlib

Inject a class with a method using dnlib


I'm trying to inject a class with a method in a file. I'm aware that there is a working solution in ConfuserEx's source code but it kinda requires editing dnlib's code which I want to avoid.

ModuleDef manifestModule = assembly.ManifestModule;
Importer importer = new Importer(manifestModule);
IMethod method = importer.Import(typeof(AntiDumpRuntime).GetMethod("Initialize"));

TypeDef type = new TypeDefUser("AntiDump");
type.Methods.Add(method.ResolveMethodDefThrow()); // dnlib.DotNet.MemberRefResolveException: 'Could not resolve method: System.Void Obfuscator.Core.Protections.AntiDump.AntiDumpRuntime::Initialize() (Obfuscator, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null)'
manifestModule.Types.Add(type);

In the above snippet I tried to do that via Importer class, but it throws an exception right on the commented row.

Here is the ConfuserEx's solution: https://github.com/yck1509/ConfuserEx/blob/master/Confuser.Core/Helpers/InjectHelper.cs And here is the modification needed to be done in dnlib: https://github.com/yck1509/dnlib/blob/master/src/DotNet/Importer.cs#L72


Solution

  • The newest version of dnlib contain the changes you require to get it working. The importer has an constructor that allows setting a ImportMapper implementation. Using this you can properly inject code with the default version of dnlib.

    I'm maintaining a fork of ConfuserEx that uses the dnlib without modifications. So it works fine.