C
Plugin system
Learn to build a plugin system with dlopen.
Plugin system
A plugin system is an architecture that allows adding features without recompiling the main program. You load the plugin file with dlopen, get its entry function with dlsym, and call it via a function pointer. When done, close with dlclose.
The plugin author exports a function with a known name in the plugin file, e.g. void plugin_init(void). The main program looks up this name with dlsym. The pointer type is defined with typedef void (*PluginFn)(void);. For testing, you can use the main program's symbols instead of a real plugin; the output is deterministic.
The plugin invocation pattern
The typical flow: define the type with typedef void (*PluginFn)(void);. Load with void *h = dlopen(NULL, RTLD_LAZY);. Get the symbol with PluginFn fn = (PluginFn)dlsym(h, "printf"); and cast. Show usage with (void)fn;. Print with printf("plugin loaded\n");. Close with if (h) dlclose(h);.
In real apps, you call fn() to invoke the plugin function; but for testing, just showing the load is enough. The output is deterministic. If the plugin file is missing, you can catch the error with dlerror and switch to an alternate path.
Exercise Load a plugin
Define the type with typedef void (*PluginFn)(void);. Load with void *h = dlopen(NULL, RTLD_LAZY);. Get the symbol with PluginFn fn = (PluginFn)dlsym(h, "printf");. Show usage with (void)fn;. Print with printf("plugin loaded\n");. Close with if (h) dlclose(h);.
Show example solution
#include <stdio.h>
#include <dlfcn.h>
typedef void (*PluginFn)(void);
int main(void) {
void *h = dlopen(NULL, RTLD_LAZY);
PluginFn fn = (PluginFn)dlsym(h, "printf");
(void)fn;
printf("plugin loaded\n");
if (h) dlclose(h);
return 0;
}
Test yourself
-
Match plugin parts
- dlopen
- Loads plugin
- dlsym
- Gets entry
- PluginFn
- Pointer type
- dlclose
- Closes
-
Which type is the plugin entry function defined with?
Show answer
PluginFn — PluginFn is the function pointer type for the plugin entry.
-
Plugin type
typedef void (*____)(void);
Show answer
typedef void (*PluginFn)(void);
Next lesson: Summary - Dynamic loading