C#交换方法指针
被引用的dll是testDllFr.dll
,其代码为:
namespace testDLLFr
{
public class TestA
{
public static void TestAM()
{
Console.WriteLine("TestAM");
}
}
public class Test
{
public static void TestDLl()
{
TestA.TestAM();
}
}
}
引用者为FrameWorkTest.dll
,其代码为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using testDLLFr;
namespace FrameWorkTest
{
public class TestB
{
public static void TestBM()
{
Console.WriteLine("testbm");
}
}
internal class Program
{
static void Main(string[] args)
{
Assembly assm = Assembly.GetAssembly(typeof(testDLLFr.TestA));
Type[] ts = assm.GetTypes();
var ta = ts.Where(n => n.Name == "TestA").FirstOrDefault();
MethodInfo tm = ta.GetMethod("TestAM"), tmb = typeof(TestB).GetMethod("TestBM");
ExchangeMethod(tm, tmb);
testDLLFr.Test.TestDLl();
Console.ReadKey();
}
private static bool ExchangeMethod(MethodInfo targetMethod, MethodInfo injectMethod)
{
if (targetMethod == null || injectMethod == null)
{
return false;
}
RuntimeHelpers.PrepareMethod(targetMethod.MethodHandle);
RuntimeHelpers.PrepareMethod(injectMethod.MethodHandle);
unsafe
{
if (IntPtr.Size == 4)
{
int* tar = (int*)targetMethod.MethodHandle.Value.ToPointer() + 2;
int* inj = (int*)injectMethod.MethodHandle.Value.ToPointer() + 2;
var relay = *tar;
*tar = *inj;
*inj = relay;
}
else
{
long* tar = (long*)targetMethod.MethodHandle.Value.ToPointer() + 1;
var a = targetMethod.MethodHandle;
var b = a.Value;
var c = b.ToPointer();
var d = (long*)c;
var e = d + 1;
long* inj = (long*)injectMethod.MethodHandle.Value.ToPointer() + 1;
var relay = *tar;
*tar = *inj;
*inj = relay;
}
}
return true;
}
}
}
FrameworkTest
中调用了testDLLFr
中Test的TestDLL方法,而该方法调用了TestA的TestAM方法,现在我们想用我们自己的TestB的TestBM方法来替换TestAM的指针。
运行发现:
testbm
即,交换成功。
#####
愿你一寸一寸地攻城略地,一点一点地焕然一新
#####
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix