/* https://stackoverflow.com/questions/7299097/dynamically-replace-the-contents-of-a-c-sharp-method
For .NET 4 and above "C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe" /unsafe+ /out:replacemethod.exe replacemethod.cs && start "replacemethod.exe" replacemethod.exe
PrintInfo: Version x64 Release 1. Replace Instance Method Class1.Demo()
Demo
Replace result: True
Foo 2. Replace Instance Overload of Method Class1.Demo(10)
Demo: 10
Replace result: True
Foo: 10 3. Replace Static Method Class1.DemoStatic()
DemoStatic
Replace result: True
FooStatic Press any key to EXIT...
*/ using System;
using System.Reflection;
using System.Runtime.CompilerServices; class Program {
public static void Main(params string[] args){
PrintInfo();
Console.WriteLine(); Test(); Console.Write("\nPress any key to EXIT...");
Console.ReadKey(true);
} public static void PrintInfo() {
Console.Write("PrintInfo: ");
if (IntPtr.Size == ) {
#if DEBUG
Console.WriteLine("Version x86 Debug");
#else
Console.WriteLine("Version x86 Release");
#endif
} else {
#if DEBUG
Console.WriteLine("Version x64 Debug");
#else
Console.WriteLine("Version x64 Release");
#endif
}
} public static void Test() {
Console.WriteLine("1. Replace Instance Method Class1.Demo()");
var o = new Class1();
o.Demo();
var r = CSharpUtils.ReplaceMethod(typeof(Class1), "Demo", typeof(Program), "Foo");
Console.WriteLine("Replace result: {0}", r);
o.Demo(); Console.WriteLine(); Console.WriteLine("2. Replace Instance Overload of Method Class1.Demo(10)");
o.Demo();
r = CSharpUtils.ReplaceMethod(typeof(Class1), "Demo", typeof(Program), "Foo", types:new Type[]{ typeof(int) });
Console.WriteLine("Replace result: {0}" ,r);
o.Demo(); Console.WriteLine(); Console.WriteLine("3. Replace Static Method Class1.DemoStatic()");
Class1.DemoStatic();
r = CSharpUtils.ReplaceMethod(typeof(Class1), "DemoStatic", typeof(Program), "FooStatic", BindingFlags.Static|BindingFlags.NonPublic|BindingFlags.Public);
Console.WriteLine("Replace result: {0}" ,r);
Class1.DemoStatic();
} private void Foo() {
Console.WriteLine("Foo");
} private void Foo(int d) {
Console.WriteLine("Foo: {0}", d);
} private static void FooStatic() {
Console.WriteLine("FooStatic");
}
} class Class1 {
public void Demo() {
Console.WriteLine("Demo");
} public void Demo(int d) {
Console.WriteLine("Demo: {0}", d);
} public static void DemoStatic() {
Console.WriteLine("DemoStatic");
}
} public static class CSharpUtils {
public static bool ReplaceMethod(Type targetType, string targetMethod, Type injectType, string injectMethod, BindingFlags bindingAttr = BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public, Binder binder = null, CallingConventions callConvention = CallingConventions.Any, Type[] types = null, ParameterModifier[] modifiers = null) {
if (types == null) {
types = Type.EmptyTypes;
}
MethodInfo tarMethod = targetType.GetMethod(targetMethod, bindingAttr, binder, callConvention, types, modifiers);
MethodInfo injMethod = injectType.GetMethod(injectMethod, bindingAttr, binder, callConvention, types, modifiers);
if (tarMethod == null || injMethod == null) {
return false;
}
RuntimeHelpers.PrepareMethod(tarMethod.MethodHandle);
RuntimeHelpers.PrepareMethod(injMethod.MethodHandle);
unsafe {
if (IntPtr.Size == ) {
int* tar = (int*)tarMethod.MethodHandle.Value.ToPointer() + ;
int* inj = (int*)injMethod.MethodHandle.Value.ToPointer() + ;
*tar = *inj;
} else {
long* tar = (long*)tarMethod.MethodHandle.Value.ToPointer() + ;
long* inj = (long*)injMethod.MethodHandle.Value.ToPointer() + ;
*tar = *inj;
}
}
return true;
}
}

C# 运行时替换方法(需要unsafe编译)的更多相关文章

  1. 1.2 - C#语言习惯 - 用运行时常量readonly而不是编译期常量const

    C#中有两种类型的常量:编译期常量和运行时常量.二者有着截然不同的行为,使用不当将会带来性能上或正确性上的问题. 这两个问题最好都不要发生,不过若难以同时避免的话,那么一个略微慢一些但能保证正确的程序 ...

  2. gohook 一个支持运行时替换 golang 函数的库实现

    运行时替换函数对 golang 这类静态语言来说并不是件容易的事情,语言层面的不支持导致只能从机器码层面做些奇怪 hack,往往艰难,但如能成功,那挣脱牢笼带来的成就感,想想就让人兴奋. gohook ...

  3. Objective-C运行时编程 - 方法混写 Method Swizzling

    摘要: 本文描述方法混写对实例.类.父类.不存在的方法等情况处理,属于Objective-C(oc)运行时(runtime)编程范围. 编程环境:Xcode 6.1.1, Yosemite,iOS 8 ...

  4. OC运行时和方法机制笔记

    在OC当中,属性是对字段的一种特殊封装手段. 在编译期,编译器会将对字段的访问替换为内存偏移量,实质是一种硬编码. 如果增加一个字段,那么对象的内存排布就会改变,需要重新编译才行. OC的做法是,把实 ...

  5. 趣谈iOS运行时的方法调用原理

    一个成熟的计算机语言必然有丰富的体系,复杂的容错机制,处理逻辑以及判断逻辑.但这些复杂的逻辑都是围绕一个主线丰富和展开的,所以在学习计算机语言的时候,先掌握核心,然后了解其原理,明白程序语言设计的实质 ...

  6. 《C#高效编程》读书笔记02-用运行时常量(readonly)而不是编译期常量(const)

    C#有两种类型的常量:编译期常量和运行时常量.两者有截然不同的行为,使用不当的话,会造成性能问题,如果没法确定,则使用慢点,但能保证正确的运行时常量. 运行时常量使用readonly关键字声明,编译期 ...

  7. MEF在运行时替换插件

    利用AppDomain的ShadowCopy特性. var setup = new AppDomainSetup { CachePath = cachePath, ShadowCopyFiles = ...

  8. c# 运行时替换某文件源代码(将XML 转换成 某个枚举并写入源文件)

    var sr = new StreamReader(Server.MapPath("~/WEB-INF/rule.config")); XmlDocument doc = new ...

  9. java 利用java运行时的方法得到当前屏幕截图的方法(转)

    将截屏图片保存到本地路径: package com.test; import java.awt.AWTException; import java.awt.Dimension; import java ...

随机推荐

  1. Java中native关键字使用

    native是与C++异构开发的时候用的.java自己开发不会使用

  2. tpot从elastic search拉攻击数据之三 用于拉取的java程序

    package download; import org.json.JSONArray; import java.io.*; import java.net.URL; import java.net. ...

  3. 我的Android进阶之旅------>Android颜色值(#AARRGGBB)透明度百分比和十六进制对应关系以及计算方法

    我的Android进阶之旅-->Android颜色值(RGB)所支持的四种常见形式 透明度百分比和十六进制对应关系表格 透明度 十六进制 100% FF 99% FC 98% FA 97% F7 ...

  4. Linux(4)- centos7安装python3、Linux下安装、配置virtualenv、确保开发环境的一致性、虚拟环境之virtualenvwrapper、vim

    一.centos7安装python3 1.下载python3的源码包 下载地址:https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz cd ...

  5. Android图片加载框架Picasso最全使用教程3

    前面我们对Picasso的用法有了一定得了解,下面就分析一下一些特殊情况下,Picasso的用法. 调用.noFade() Picasso的默认图片加载方式有一个淡入的效果,如果调用了noFade() ...

  6. android 6 (API 23) 及更高版本 面向 NDK 开发者的 Android 变更

    Android N 已经出来,有了好大的变化,对于我们开发者来说,最大的影响莫过于**NDK**相关东西. 以下是在中国谷歌开发者社区看到的.里面有好多的变化,欢迎大家来讨论. 发布人:开发顾问 Dm ...

  7. ES6简单入门

    let let命令用来声明块级作用域. 以前的JavaScript只有全局作用域和函数作用域, 没有块级作用域. // 示例1: if (1) { var a = "hello"; ...

  8. python识别验证码

    1.tesseract-ocr安装 tesseract-ocr windows下载地址 http://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr- ...

  9. 11 Spring框架 SpringDAO的JdbcTemplate

    上几个章节我们探讨了Spring的IoC和AOP,这是Spring的重点,但是Spring对jdbc的支持同样我们也不能忘记,毕竟我们还要通过Spring来管理DAO框架(例如Hibernate或者M ...

  10. HDU - 4407 Sum (容斥)

    题意:初始序列[1..N](1<=N<=4e5),支持两种操作:1.求区间[x,y]内与p互素的数之和: 2.将x位置的数变为c. 分析:很容易把人骗到线段树的思维中,而实际上操作2单点的 ...