我最近在和一些人谈论我正在编写的程序时听到了“hook”这个词。我不确定这个术语到底意味着什么,尽管我从对话中推断钩子是一种函数类型。我寻找一个定义,但无法找到一个好的答案。有没有人能告诉我这个术语的一般含义,或者举个小例子来说明这个定义?


当前回答

一个函数,允许您提供另一个函数,而不仅仅是一个值作为参数,本质上是扩展它。

其他回答

通常挂钩指的是Win32消息挂钩或Linux/OSX的等等物,但更一般的挂钩只是通知另一个对象/窗口/程序等,当指定的操作发生时,你想被通知。例如:让系统上的所有窗口在即将关闭时通知您。

作为一般规则,钩子有点危险,因为在不了解它如何影响系统的情况下这样做可能会导致不稳定或至少是意想不到的行为。在某些情况下,它也非常有用。例如:FRAPS使用它来确定应该在哪个窗口显示FPS计数器。

简单的说:

钩子是在现有代码之前、之后或代替现有代码执行自定义代码(函数)的一种方法。例如,为了在继续正常登录过程之前执行验证码函数,可以编写一个函数“hook”到登录过程中。

Hook表示在代码中分派某个类型的事件的位置,如果该事件在此之前已使用适当的函数进行回调,那么它将由这个已注册的函数处理,否则什么都不会发生。

A chain of hooks is a set of functions in which each function calls the next. What is significant about a chain of hooks is that a programmer can add another function to the chain at run time. One way to do this is to look for a known location where the address of the first function in a chain is kept. You then save the value of that function pointer and overwrite the value at the initial address with the address of the function you wish to insert into the hook chain. The function then gets called, does its business and calls the next function in the chain (unless you decide otherwise). Naturally, there are a number of other ways to create a chain of hooks, from writing directly to memory to using the metaprogramming facilities of languages like Ruby or Python.

钩子链的一个例子是MS Windows应用程序处理消息的方式。处理链中的每个函数要么处理消息,要么将其发送给链中的下一个函数。

简而言之,您可以更改API调用的代码,例如MessageBox,使其执行由您编辑的不同函数(全局适用于系统范围,本地适用于进程范围)。