C# 运行时替换方法(需要unsafe编译)
/* 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.2 - C#语言习惯 - 用运行时常量readonly而不是编译期常量const
C#中有两种类型的常量:编译期常量和运行时常量.二者有着截然不同的行为,使用不当将会带来性能上或正确性上的问题. 这两个问题最好都不要发生,不过若难以同时避免的话,那么一个略微慢一些但能保证正确的程序 ...
- gohook 一个支持运行时替换 golang 函数的库实现
运行时替换函数对 golang 这类静态语言来说并不是件容易的事情,语言层面的不支持导致只能从机器码层面做些奇怪 hack,往往艰难,但如能成功,那挣脱牢笼带来的成就感,想想就让人兴奋. gohook ...
- Objective-C运行时编程 - 方法混写 Method Swizzling
摘要: 本文描述方法混写对实例.类.父类.不存在的方法等情况处理,属于Objective-C(oc)运行时(runtime)编程范围. 编程环境:Xcode 6.1.1, Yosemite,iOS 8 ...
- OC运行时和方法机制笔记
在OC当中,属性是对字段的一种特殊封装手段. 在编译期,编译器会将对字段的访问替换为内存偏移量,实质是一种硬编码. 如果增加一个字段,那么对象的内存排布就会改变,需要重新编译才行. OC的做法是,把实 ...
- 趣谈iOS运行时的方法调用原理
一个成熟的计算机语言必然有丰富的体系,复杂的容错机制,处理逻辑以及判断逻辑.但这些复杂的逻辑都是围绕一个主线丰富和展开的,所以在学习计算机语言的时候,先掌握核心,然后了解其原理,明白程序语言设计的实质 ...
- 《C#高效编程》读书笔记02-用运行时常量(readonly)而不是编译期常量(const)
C#有两种类型的常量:编译期常量和运行时常量.两者有截然不同的行为,使用不当的话,会造成性能问题,如果没法确定,则使用慢点,但能保证正确的运行时常量. 运行时常量使用readonly关键字声明,编译期 ...
- MEF在运行时替换插件
利用AppDomain的ShadowCopy特性. var setup = new AppDomainSetup { CachePath = cachePath, ShadowCopyFiles = ...
- c# 运行时替换某文件源代码(将XML 转换成 某个枚举并写入源文件)
var sr = new StreamReader(Server.MapPath("~/WEB-INF/rule.config")); XmlDocument doc = new ...
- java 利用java运行时的方法得到当前屏幕截图的方法(转)
将截屏图片保存到本地路径: package com.test; import java.awt.AWTException; import java.awt.Dimension; import java ...
随机推荐
- Python 模块之 time & datetime
Python 中提供了对时间日期的多种多样的处理方式,主要是在有 time 和 datetime 两个模块. time 在 Python 文档里,time 是归类在 Generic Operating ...
- matlab出错及改正
1 使用小波分析时,出现下面错误: 错误使用 wavedec需要的 X 应为 矢量.出错 wavedec (line 34)validateattributes(x,{'numeric'},{'vec ...
- python16_day11【MQ、Redis、Memcache】
一.RabbitMQ 是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议. MQ全称为Message Queue, 消息队列(MQ)是一种应 ...
- 在Windows上以服务方式运行 Redis
ServiceStack.Redis 使用教程里提到Redis最好还是部署到Linux下去,Windows只是用来 做开发环境,现在这个命题发生改变了,在Windows上也可以部署生产环境的Redis ...
- 9. Palindrome Number(判断整型数字是否是回文,直接暴力即可)
Determine whether an integer is a palindrome. Do this without extra space. class Solution: def isPal ...
- hadoop14---centos 安装activemq
创建activemq目录 [root@node1 ~]# mkdir -p /usr/local/activemq 狐火下载activemq,从用户/download目录把文件cp到/usr/loca ...
- 【Java】Swing+IO流实现一个简单的文件加密程序(较完整版)
留着参考 beans package com.my.bean; import java.io.Serializable; public class EncryptedFile implements S ...
- Linux:查看磁盘空间占用情况
Linux:查看磁盘空间占用情况 工作中有时被分配的测试机空间不大,经常遇到磁盘空间占满的情况.排查过程如下: 一.首先使用df -h 命令查看磁盘剩余空间,通过以下图看出/目录下的磁盘空间已经被占满 ...
- 《React-Native系列》RN与native交互与数据传递
RN怎么与native交互的呢? 下面我们通过一个简单的Demo来实现:RN页面调起Native页面,Native页面选择电话本数据,将数据回传给RN展示. 首先是 Native侧 1.MainAct ...
- 混合开发的大趋势之 一个Android程序员眼中的 React.js 箭头函数,const, PropTypes
转载请注明出处:王亟亟的大牛之路 昨天写了篇React.js的开头之作,讲了讲块级作用域和let,先安利:https://github.com/ddwhan0123/Useful-Open-Sourc ...