Search code examples
c++windowsmodular

Simple modular guide in C/++?


I think modular is the correct term; to give a basic example if I was to create an encryption application which you could type in like notepad, and then save encrypted, however under the save menu there are options to save for the encryption methods that you have plugins for like AES, Blowfish etc, and also allow new methods to be coded into a plugin and distributed without having to recompile the main application.

I've found a couple of explanations online but I'm mostly struggling to get my head around how you would get new options to appear under the save menu that originally didn't exist (this maybe more a Windows application question), if you get what I mean.

Seeing as modular development seems to be very platform specific I'll stick with Windows examples for now and hopefully try and scope out after that.


Solution

  • Assuming Win32api, you do something like this:

    • Have a plugins directory for your application.
    • On load of your application, list all files in that directory
    • Any with the extension DLL, you load with the LoadLibrary call.
    • You get some information from the dll that tells you what the plugin's name is
    • You create menus/ui changes appropriately.

    Now, when you create your dll, you have a standard set of functions common to all plugins. Or, a standard set of functions per type of plugin and a function that identifies this with your application. This way, you can test each plugin is of the correct form and call the methods in the dynamic library on the fly without having to compile / link them in to your main program.

    The routine is broadly similar on any platform that supports shared libraries (DLLs, so's etc).

    As a code example for what I mean, you might have a plugin.h file like this:

    #ifndef PLUGIN_H_
    #define PLUGIN_H_
    
    #define PLUGIN_CRYPTO   1
    #define PLUGIN_FORMAT   2
    #define PLUGIN_EXAMPLE  3
    
    #endif 
    

    Then you #include this header in both your main program and any plugins you create. In plugin-dll.cpp (example again) you have a method like this:

    int GetPluginType()
    {
        return PLUGIN_CRYPTO;
    }
    

    Then you can switch between the results of this function and assign function pointers to the correct routines you want to run.

    More info for implenentation:

    Just because, Linux (POSIX) equivalents:

    • dlopen - Dynamic library open.
    • dlsym - Equivalent to GetProcAddress - get function ptr to symbol name.
    • dlclose - Equivalent to FreeLibrary