Function hooking in C++?

后端 未结 7 677
一整个雨季
一整个雨季 2020-12-13 02:11

With \"hooking\" I mean the ability to non-intrusively override the behavior of a function. Some examples:

  • Print a log message before and/or after the function
相关标签:
7条回答
  • 2020-12-13 03:05

    IMO this is an incredibly useful feature, so why is it not a C++ language feature? Are there any reasons that prevent this from being made possible?

    C++ the language does not provide any means to do so directly. However, it also does not pose any direct constraint against this (AFAIK). This type of feature is easier to implement in an interpreter than in native code, because the interpret is a piece of software, not a CPU streaming machine instructions. You could well provide a C++ interpreter with support for hooks if you wanted to.

    The problem is why people use C++. A lot of people are using C++ because they want sheer execution speed. To achieve that goal, compilers output native code in the operating system's preferred format and try to hard code as much stuff into the compiled executable file. The last part often means computing addresses at compile/link time. If you fix a function's address at that time (or even worse, inline the function body) then there is no more support for hooks.

    That being said, there are ways to make hooking cheap, but it requires compiler extensions and is totally not portable. Raymond Chen blogged about how hot patching is implemented in the Windows API. He also recommends against its use in regular code.

    0 讨论(0)
提交回复
热议问题