有没有办法改进这个库中的挂钩功能

Is there a way to improve the hooking functionality in this library

Link: https://github.com/xcvd/Detours

在Hooks.cs我们调用了原来的函数

在这个库中,它是通过将挂钩地址的字节反转回原始字节来完成的。

这里的问题是,如果您每 500 毫秒或更短时间有 1000 次调用,那么它会导致错误,并会造成内存问题和崩溃,或者由于未接来电而导致非常糟糕的错误。

那么有什么办法可以避免这种情况吗?

我很幸运地在没有像每秒 50 个调用这样的函数上使用这个库。

这是一种与非托管 .net 交互的非常好的方式。 比 EasyHook、Deviare 等简单得多。

使用 x86 应用程序。

public object CallOriginal(params object[] args)
        {
            this.Uninstall();
            var ret = this.targetDelegate.DynamicInvoke(args);
            this.Install();
            return ret;
        }        
public bool Install()
        {
            try
            {
                Memory.Write(this.target, this.newBytes);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }        
public bool Uninstall()
        {
            try
            {
                Memory.Write(this.target, this.originalBytes);                
                this.IsInstalled = false;                
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

挂钩就是这样完成的。


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

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

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

想出如何解决。 我只需要分配一个新的内存区域,然后复制被覆盖的原始函数字节,并在被覆盖的字节之后跳回。 我必须定义多少字节,因为我没有逻辑来检测正在使用的操作码。 我还通过检测字节是否为 0 来进行调整以允许使用原始方法或新方法。