我最近在和一些人谈论我正在编写的程序时听到了“hook”这个词。我不确定这个术语到底意味着什么,尽管我从对话中推断钩子是一种函数类型。我寻找一个定义,但无法找到一个好的答案。有没有人能告诉我这个术语的一般含义,或者举个小例子来说明这个定义?
当前回答
简而言之,您可以更改API调用的代码,例如MessageBox,使其执行由您编辑的不同函数(全局适用于系统范围,本地适用于进程范围)。
其他回答
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应用程序处理消息的方式。处理链中的每个函数要么处理消息,要么将其发送给链中的下一个函数。
钩子是一类允许基本代码调用扩展代码的函数。这在核心开发人员希望在不暴露代码的情况下提供可扩展性的情况下非常有用。
钩子的一个用法是在电子游戏mod开发中。游戏可能不允许mod开发者扩展基本功能,但核心mod库开发者可以添加钩子。有了这些钩子,独立开发者可以在任何想要的事件中调用他们的自定义代码,比如游戏加载、库存更新、实体交互等。
一种常见的实现方法是给函数一个空的回调列表,然后公开扩展回调列表的能力。基本代码将始终在相同的适当时间调用该函数,但如果是空回调列表,则该函数不执行任何操作。这是有意为之。
然后,第三方就有机会编写额外的代码,并将他们的新回调添加到钩子的回调列表中。仅仅通过一个可用钩子的引用,它们就以最小的风险扩展了基本系统的功能。
hook不允许开发人员做任何其他结构和接口不能做的事情。它们是需要考虑任务和用户(第三方开发人员)的选择。
澄清一下:钩子允许扩展,并且可以使用回调来实现。回调函数通常只是一个函数指针;函数的计算地址。其他答案/评论似乎有些混乱。
答案很多,但没有例子,所以添加一个虚拟的:下面的complated_func提供了两个钩子来修改它的行为
from typing import List, Callable
def complicated_func(
lst: List[int], hook_modify_element: Callable[[int], int], hook_if_negative=None
) -> int:
res = sum(hook_modify_element(x) for x in lst)
if res < 0 and hook_if_negative is not None:
print("Returning negative hook")
return hook_if_negative
return res
def my_hook_func(x: int) -> int:
return x * 2
if __name__ == "__main__":
res = complicated_func(
lst=[1, 2, -10, 4],
hook_modify_element=my_hook_func,
hook_if_negative=0,
)
print(res)
简而言之,您可以更改API调用的代码,例如MessageBox,使其执行由您编辑的不同函数(全局适用于系统范围,本地适用于进程范围)。
简单的说:
钩子是在现有代码之前、之后或代替现有代码执行自定义代码(函数)的一种方法。例如,为了在继续正常登录过程之前执行验证码函数,可以编写一个函数“hook”到登录过程中。