是否可以定义一个指向构造函数的函数指针?
我使用带有显式链接的共享库(使用 dlopen 加载共享库),以便在 C++ 中实现插件模式。
是否可以定义一个指向共享库中定义的类的构造函数的函数指针,或者我必须在共享库中定义工厂方法,该方法将从共享库中实例化(并初始化)类的对象?当然,在我的主应用程序中,我将定义一个指向工厂方法的函数指针,并且该方法将返回我需要的类的实例。
干杯
I'm using shared library with explicit linking (loading shared lib with dlopen
) in order to implement plugin pattern in C++.
Is it possible to define a function pointer to a constructor of a class defined in the shared library or I would have to define factory method, within shared lib, that would instantiate (and initialize) object of a class from shared lib? Of course in my main app, then, I would define a function pointer to a factory method, and that method would return an instance of the class I need.
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题的答案是否定的,您不能定义指向构造函数的成员或函数指针。
对于 dlopen,您需要提供一个带有 c 链接的函数并动态加载它,您可以使用它来创建对象,并且还需要另一个函数来删除对象。
有关更多信息此处
The answer to the question is no, you can not define a member or function pointer to the constructor.
For dlopen, you need to provide a function with c linkage and load it dynamically, which you can use to create the objects, and you also need another function to delete objects.
More about it here
使用 dlsym() 获取指针时,您需要注意名称修改问题。依赖某些特定的修饰方法并不是一个好主意,它们太多样化了。因此,唯一合理的做法是将插件接口公开为 extern "C" { ... },并在构造函数上使用工厂函数包装器。
You'd need to be aware of the name mangling problems when fetching pointers with dlsym(). It's not a good idea to rely on some specific mangling method, they're all too diverse. So the only reasonable thing to do is to expose your plugin interface as extern "C" { ... }, with factory function wrappers over constructors.