是否可以在运行时替换方法? [英] Is it possible to replace a method at runtime?
问题描述
我想创建一个能够在运行时覆盖方法的插件系统.
I want to make a plugin system with the capability to override a method at runtime.
有些答案说了函数指针,但是定义的函数或类呢?
Some answers say function pointers, but how about a defined function or class?
赞:
class foo
{
public:
bar(int foobar);
}
是否有办法获取函数指针或替换它?
Is there a way to get function pointer for that, or replace it?
顺便说一句,钩子不被认为是答案,因为它是特定于平台的并且非常危险.
BTW, hooking is not considered an answer because it's very platform specific and dangerous.
推荐答案
运行时功能替换"可以通过以下几种技术之一来实现:
Runtime function "replacement" can be achieved with one of several techniques:
- 多态
- 标准库工具,例如
std::function
- 第三方库或特定于平台的技术来翻译或调度函数调用.
- Polymorphism
- Standard library facilities such as
std::function
- Third party libraries or platform specific techniques to translate or dispatch function calls.
哪种选择更好,很大程度上取决于预期的用途和目标环境.例如;插件系统可以很好地利用多态性(通过适当的工厂,甚至可能与模板方法模式),而内部函数路由可以使用std::function
.
On which option is better is highly dependent on the intended use and target environments. For example; plugin systems could well make use of polymorphism (with the appropriate factories and possibly even combined with the template method pattern) whilst internal function routing could use std::function
.
这些技术并不会真正替换"任何功能,而是可以在运行时进行设置以根据需要路由功能调用.
These techniques wouldn't really "replace" any of the functions, but rather can be set up at runtime to route the function call as required.
注意我专注于问题的C ++方面(被标记为C和C ++,但示例代码为C ++).
Note I've focused on the C++ aspects of the question (it was tagged C and C++ but the sample code is C++).
这篇关于是否可以在运行时替换方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!