简体   繁体   中英

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. To make the development easier i want to create an c++ "api". To do this I created base classes with virtual functions (required functions abstract) and call this functions from the plugin c-file. This "api" should be in a static library file.

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:

// 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. So the methods you need to export from the plugin you should put in the BaseClass and make them virtual.

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.

Note2: Don't forget to make the destructor of your base class virtual.

Note3: You should be really careful when using C++ API with dynamic loading libraries. The problem is that compiler mangles the C++ class and function names. 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. Please look here for more info on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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