C 中的后期绑定
C语言如何实现后期绑定? 任何人都可以提供一个例子吗?
我认为可以使用 dlopen 和 dlsym 来实现,但我不确定。如果我错了,请纠正我!
How can late binding can be achieved in C language?
Can anybody please provide an example.
I think it can be achieved using dlopen
and dlsym
but I am not sure about it.Please correct me if I am wrong!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
后期(又称为动态)绑定本身与动态加载模块(这就是 dlopen 和 dlsym 的作用)没有任何关系。相反,它是将调用哪个函数的决定延迟到运行时。
在 C 中,这是使用函数指针来完成的(这也是几乎所有 C++ 实现对虚拟函数执行此操作的方式)。
模拟这种情况的一种方法是传递函数指针结构,然后仅通过给定的函数指针调用函数。
一个例子:
Late (AKA Dynamic) Binding doesn't have anything to do with dynamically loaded modules (which is what
dlopen
anddlsym
are about) per se. Instead, it is about delaying the decision about which function is called until runtime.In C, this is done using function pointers (which is also how virtually any C++ implementation does it for virtual functions).
One way to emulate this is to pass structs of function pointers around and then only call functions via the given function pointers.
An example:
@Frerich Raabe:基本的后期绑定机制可以按照您所说的方式实现,但是您可以使用 dlopen/dlclose/dlsym 和函数指针的组合来获得类似的内容:
我认为这就是本杰明·巴顿正在寻找的东西。
@Frerich Raabe: The basic late binding mechanism can be implemented as your said, but you can use a combination of dlopen/dlclose/dlsym and pointers to function to get something like:
I think this is what Benjamin Button is looking for.
正如 Frerich Raabe 提到的,这一切都是为了延迟调用哪个函数的决定,仅此而已。
为了强调它是 C/C++ 中的通用机制,我喜欢考虑下面的纯 C(和 C 风格编码,即 - 不存在任何“OO 概念”),以便掌握早期/后期绑定概念:
Just as Frerich Raabe mentioned, it is all about delaying the decision of what function to invoke, that's it.
To emphasis that it is a general mechanism in C/C++, I love to consider the below pure C (and C style coding, i.e. - no presence of any "OO concepts") in order to grasp the early/late binding concept: