小编Luc*_*ani的帖子

在 C# 中运行时挂钩托管方法

我有一个密封类,在程序集中有一个公共方法,我想添加一个日志系统,但不幸的是我没有源代码。因此,我尝试在特定的日志记录方法上绕过此方法,并在退出时调用原始方法。挂钩工作正常,但我无法获取任何类型的参数,或者至少我得到了完全错误的东西。

我也不能使用任何类型的注入或像 PostSharp 这样的库,所以我想知道这种东西是否可以在运行时以某种方式实现,或者我可以放弃吗?

为了给您提供更多详细信息,我将在下面粘贴一些代码部分:

public Hook(Delegate target, Delegate hook)
{
  this.target = Marshal.GetFunctionPointerForDelegate(target);
  targetDelegate = target;
  this.hook = Marshal.GetFunctionPointerForDelegate(hook);

  originalBytes = new byte[6];
  Marshal.Copy(this.target, originalBytes, 0, 6);

  byte[] hookPointerBytes = BitConverter.GetBytes(this.hook.ToInt32());
  // Jump
  newBytes = new byte[]
  {
    0x68, hookPointerBytes[0], hookPointerBytes[1], hookPointerBytes[2], hookPointerBytes[3], 0xC3
  };
}

public object CallOriginal(params object[] args)
{
  // Remove the patch
  Uninstall();
  // Invoke the original method
  object ret = targetDelegate.DynamicInvoke(args);
  // Re-apply the patch
  Install();
  return ret;
}


public sealed class Foo
{ …
Run Code Online (Sandbox Code Playgroud)

c# methods hook detours managed

5
推荐指数
1
解决办法
7240
查看次数

标签 统计

c# ×1

detours ×1

hook ×1

managed ×1

methods ×1