• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Mono.Cecil的注入方法

用户头像
it1352
帮助1

问题说明

如何使用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.

正确答案

#1

要注入方法,您需要获取要添加的类型,然后再添加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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfjgji
系列文章
更多 icon
同类精品
更多 icon
继续加载