简体   繁体   English

C ++共享库导出功能

[英]C++ shared library export function

I want to write an plugin for an application. 我想为应用程序编写一个插件。 The application brings a plugin header- and c-file written with the exported functions to fill. 该应用程序将使用导出的函数编写的插件头文件和c文件进行填充。 To make the development easier i want to create an c++ "api". 为了使开发更容易,我想创建一个c ++“ api”。 To do this I created base classes with virtual functions (required functions abstract) and call this functions from the plugin c-file. 为此,我使用虚函数(必需的函数抽象)创建了基类,并从插件c文件调用此函数。 This "api" should be in a static library file. 此“ api”应位于静态库文件中。

The real plugin (a shared library) should include this static library, derive and implement it needed classes. 真正的插件(共享库)应包括此静态库,派生并实现所需的类。

Now my problem: how do I export the function from the included static lib in the shared lib (so the application calls the functions from the static lib)? 现在我的问题是:如何从共享库中包含的静态库中导出函数(因此应用程序从静态库中调用函数)? is this possible? 这可能吗?

Usually if you want to have a plugin mechanism with C++ then this is the most common way of doing it: 通常,如果您希望使用C ++的插件机制,这是最常用的方法:

// Plugin file
extern "C" BaseClass* create()
{
    return new DerivedClass;
}

extern "C" void destroy(BaseClass* base)
{
    delete base;
}

Then in your code which uses the plugin you're actually dealing with the BaseClass without caring about with which exactly DerivedClass it is currently pointing to. 然后,在使用该插件的代码中,您实际上是在处理BaseClass而不必关心它当前指向的是哪个DerivedClass So the methods you need to export from the plugin you should put in the BaseClass and make them virtual. 因此,您需要从插件中导出的方法应该放在BaseClass并使它们虚拟化。

Note1: Make sure that you always call destroy function instead of primarily using delete as it may be overloaded in your application but not in the plugin library or vice versa. 注意1:请确保始终调用destroy函数,而不是主要使用delete因为它可能会在您的应用程序中重载,但在插件库中不会,反之亦然。

Note2: Don't forget to make the destructor of your base class virtual. 注意2:不要忘记将基类的析构函数设为虚拟。

Note3: You should be really careful when using C++ API with dynamic loading libraries. 注意3:将C ++ API与动态加载库一起使用时,您应该非常小心。 The problem is that compiler mangles the C++ class and function names. 问题在于,编译器会破坏C ++类和函数名。 So if you happen to compile your application and the plugin library with the different compilers or even with the different versions of the same compiler then the linker may not be able to resolve the function name correctly to find it in plugin's library. 因此,如果您碰巧使用不同的编译器甚至同一编译器的不同版本来编译应用程序和插件库,则链接器可能无法正确解析函数名以在插件的库中找到它。

Note4: The same problem above can happen if you do some changes in your application thus making the compiler to change the name mangling for the existing functions. 注意4:如果您在应用程序中进行了一些更改,从而使编译器更改了现有函数的名称,则可能会发生上述相同的问题。 Please look here for more info on this. 在这里查看更多信息。

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

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