是否可以定义一个指向构造函数的函数指针?

发布于 2024-10-07 20:51:31 字数 191 浏览 0 评论 0原文

我使用带有显式链接的共享库(使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情感失落者 2024-10-14 20:51:31

问题的答案是否定的,您不能定义指向构造函数的成员或函数指针。

对于 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

中二柚 2024-10-14 20:51:31

使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文