简体   繁体   English

C ++继承和动态库加载

[英]C++ inheritance and dynamic library loading

I'm trying to create modular application in C++. 我正在尝试在C ++中创建模块化应用程序。 Everything works fine when linked statically, but I want to achieve plug-in architecture (using dlopen or LoadLibrary). 静态链接时一切正常,但是我想实现插件体系结构(使用dlopen或LoadLibrary)。

All base classes are located in host apllication and these classes are extended in plug-in modules. 所有基类都位于主机应用程序中,并且这些类在插件模块中扩展。 Modules are loaded at run-time. 模块在运行时加载。

Application                Module
----------------           -------------------
| BaseClass1   |           | ExtendedClass1  |
| BaseClass2   |           | ExtendedClass2  |
| BaseClass3   |           | ExtendedClass3  |
----------------           -------------------

But when I try to compile module, linker obviously can't find references to BaseClass methods. 但是,当我尝试编译模块时,链接器显然找不到对BaseClass方法的引用。

Can I somehow tell linker not to link these classes at compile time and let OS to link them on load in run-time? 我能以某种方式告诉链接器不要在编译时链接这些类,而让OS在运行时在加载时链接它们吗? Or should I use different approach and move BaseClasses to some core library and link both the application and module to this core library? 还是应该使用其他方法,将BaseClasses移至某个核心库,然后将应用程序和模块都链接到该核心库?

The better approach for this is to have the base class in a core library which is usable both by the Application and the Module. 更好的方法是将基类放在核心库中,该库可供应用程序和模块使用。 However, please note that dlopen and LoadLibrary both can load only functions, so possibly you will need to have a function in your plugin library which will create your desired object. 但是,请注意, dlopenLoadLibrary都只能加载函数,因此可能需要在插件库中有一个函数,该函数将创建所需的对象。

Just like you said, use the core approach. 就像您说的那样,请使用核心方法。 Create a common/core directory, which has all the header files of BaseClass1 to BaseClass3. 创建一个common / core目录,其中包含BaseClass1到BaseClass3的所有头文件。 When you compile host application, it will have access to this common directory. 当您编译主机应用程序时,它将有权访问该公共目录。 When you compile plug-in, it will also have access to this common directory. 编译插件时,它也可以访问此公共目录。
If you need to release host binary to external customers, you will also include the common directory, so that external customer can program their own plug-in. 如果需要将主机二进制文件发布给外部客户,则还将包括公用目录,以便外部客户可以编写自己的插件。 This is how we do it. 这是我们的做法。 Not the best solution, but it works. 不是最好的解决方案,但它可以工作。

如果您确实想使用dlopen实现插件体系结构,请查看此答案Linux上的C ++动态共享库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM