Jump to content
View in the app

A better way to browse. Learn more.

Tuts 4 You

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

[dnlib] Injecting class with method.

Featured Replies

Posted

Hello guys. I have some problems with injecting new class with one method inside it. Basicly this class is placed in my project and i need to insert it in assembly using dnlib, then call the method from it from constructor.


My code sample:



AssemblyDef assembly = AssemblyDef.Load(FilePath);
ModuleDef module = assembly.Modules[0];
Importer importer = new Importer(module); // Create new importer.
IMethod meth = importer.Import(typeof(MyClass).GetMethod("Initialize")); // Trying to import initialization method and then place it into a new class.
TypeDef type = new TypeDefUser("NewClass"); // Creating new type.
type.Attributes = TypeAttributes.Class; // Setting class attribute.
type.Methods.Add(meth.ResolveMethodDef()); // Catching Null exception here.
module.Types.Add(type); // Adding new type into our module.
////////////////////////////////////
MethodDef cctor = module.GlobalType.FindOrCreateStaticConstructor();
cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, meth)); // Need to call that method here.

So, i also have another question opposite topic subject. How can i enumerate all assembly references with dnlib?


A proper way of doing it is complicated since you'd have to clone the type, its members etc. A simple hack is to just remove the type from the original assembly and insert it in the new assembly.

var type = xxxx;

module.Types.Remove(type);

newModule.Types.Add(type);

If that type references other types, you'd have to do the same thing for every type. ConfuserEx has some code that imports its protection code into the protected application. Maybe that could be used if you want a better solution.

var m = module as ModuleDefMD;// if you've loaded it from disk / byte[] / stream, this will never be null

if (m == null)

throw new ...

foreach (var asmRef in m.GetAssemblyRefs())

Console.WriteLine("{0", asmRef);

Create an account or sign in to comment

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.