Mono.Cecil的注入方法 [英] Inject Method with Mono.Cecil

查看:511
本文介绍了Mono.Cecil的注入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用mono.cecil将自定义方法注入.net程序集中,然后在入口点调用它? 构建二进制文件后,我想这样做以实现安全性方法.

How can I inject a custom method into a .net assembly using mono.cecil, and then call it in the entrypoint? I like to do this to implement security methods after the binary is built.

推荐答案

要注入方法,您需要获取要添加的类型,然后再添加MethoDefinition.

To inject method you need to get the type you want to add it the method and then add a MethoDefinition.

var mainModule = ModuleDefinition.ReadModule(assemblyPath);
var type = module.Types.Single(t => t.Name == "TypeYouWant");
var newMethodDef= new MethodDefinition("Name", MethodAttributes.Public, mainModule.TypeSystem.Void);
type.Methods.Add(newMethodDef);

要从入口点调用此方法,需要获取入口点MethodDefinition和新注入的MethodReference,并在入口点方法中添加指令以调用新的注入方法.

To call this method form the entry point, you need to get the entry point MethodDefinition and the new injected MethodReference and add instruction in the entry point method to call the new injected method.

var newMethodRef = type.Methods.Single(m => m.Name == "Name").Resolve();
var entryPoint= type.Methods.Single(m => m.Name == "YourEntryPoint");
var firstInstruction = entryPoint.Body.Instructions.First();
var il = entryPoint.Body.GetILProcessor();
il.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Callvirt, newMethodRef));
mainModule.Write(assemblyPath);

注意:是的,我知道它的C#而不是VB,但是我敢肯定,一旦您有了主意,便可以轻松将其转换为VB.

Note: Yes I know its C# and not VB but I'm sure once you got the idea you can easily convert it to VB.

这篇关于Mono.Cecil的注入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆