我最近在和一些人谈论我正在编写的程序时听到了“hook”这个词。我不确定这个术语到底意味着什么,尽管我从对话中推断钩子是一种函数类型。我寻找一个定义,但无法找到一个好的答案。有没有人能告诉我这个术语的一般含义,或者举个小例子来说明这个定义?
当前回答
简而言之,您可以更改API调用的代码,例如MessageBox,使其执行由您编辑的不同函数(全局适用于系统范围,本地适用于进程范围)。
其他回答
从本质上讲,它是代码中的一个地方,允许您进入一个模块来提供不同的行为或在发生某事时做出反应。
编程中的钩子是一种技术,它使用所谓的钩子来创建一个过程链作为事件处理程序。
简单的说:
钩子是在现有代码之前、之后或代替现有代码执行自定义代码(函数)的一种方法。例如,为了在继续正常登录过程之前执行验证码函数,可以编写一个函数“hook”到登录过程中。
在Drupal内容管理系统中,“hook”有一个相对特定的含义。当内部事件发生时(例如内容创建或用户登录),模块可以通过实现一个特殊的“钩子”函数来响应该事件。这是通过命名约定完成的——例如,用户登录事件的[your-plugin-name]_user_login()。
由于这种惯例,底层事件被称为“钩子”,并在Drupal的API文档中以“hook_user_login”和“hook_user_authenticate()”这样的名称出现。
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应用程序处理消息的方式。处理链中的每个函数要么处理消息,要么将其发送给链中的下一个函数。