覆盖 C++动态加载功能
我有程序A,其中实现了函数Foo。 程序 A 能够在运行时动态加载 dll。
我目前正在编写程序B,它被编译成dll,因此程序A能够加载它。
我想做的是,以某种方式“覆盖”程序 B 中的函数 Foo ,因此当从程序 A 调用它时,会调用与程序 A 中实现的代码不同的代码。
A 找到了一些关于蹦床函数:http://en.wikipedia.org/wiki/Trampoline_%28computers%29< /a>
我的问题是,这可能吗?如何?
谢谢, krisy
编辑:我有程序A的源代码,但我不被允许修改它。因此,重新定义程序 A 的结构是不可能的:-(
编辑:我需要一个 - 最好 - 开源、跨平台的解决方案(或者至少需要在 Linux 系统下工作)
I have Program A, in which function Foo is implemented.
Program A is able to load dll's dynamicly, durring runtime.
I'm currently writing Program B, which is compiled into a dll, so Program A is able to load it.
What I would like to do, is to "override" function Foo in Program B somehow, so when it is called from Program A, a different code is invoked from the one, that is implemented in Program A.
A found some referencing topic about trampuline functions: http://en.wikipedia.org/wiki/Trampoline_%28computers%29
My question is, is it possible? How?
Thanks,
krisy
Edit: I have the source code of Program A, but I'm not allowed to modidy this. So redefining the structure of program A is out of the question :-(
Edit: I need a - preferably - open source, cross-platform solution (or at least needs to work under linux systems)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
仅当您要覆盖的函数位于程序 A 和 B 共用的外部 DLL 中时,这才是可能的。
在程序 A 内部实现该函数并在程序 B 的 DLL 中重新定义它是行不通的,因为函数已经定义了。动态链接器只会重新绑定未定义的函数。
任何解决方案都将永远是一个黑客。
最好使用函数指针或适当的类设计并创建一个以干净的方式解决问题的体系结构。
This is only possible if the function you want to override would live in an external dll common to both program A and B.
Having the function implemented inside the Program A and redefining it in the DLL for Program B it won't work, because the function is already defined. The dynamic linker will only rebind the undefined functions.
Any solution would always be an hack.
It is better to use function pointers or proper class design and create an architecture that solves you problem in a clean way.
另一种简单的方法是使用函数指针,模块A会要求B获取函数指针并调用它。
这种技术在C中多用于模拟多态,但如果你使用C++我建议你使用继承;
the other simple way is to use function pointer, and the Module A will ask B to get the function pointer and invoke it.
This technique is mostly used in C to simulate polymorphism , but I suggest you to use inheritance if you use C++;
您可以使用 Detours 来做到这一点。
编辑:
LD_PRELOAD
可能会帮助您完成同样的技巧。 (示例取自什么是 LD_PRELOAD 技巧?)You could use Detours to do that.
Edit:
LD_PRELOAD
might help you doing the same kind of trick. (Exemple taken from What is the LD_PRELOAD trick?)或者一直通过某个指针调用 Foo 并在加载 DLL 时重新定义该指针。
Detours重写了运行过程中的原有功能。这当然也是一种选择,但只是自修改代码的另一种形式,存在导致自修改代码过时的所有问题。
or call
Foo
via some pointer all the time and redefine that pointer when loading the DLL.Detours rewrites the original functions in the running process. That is of course also an option, but is just another form of self-modifying code with all the problems that made self-modifying code go out of fashion.