Reputation: 87250
I have a host binary executable that defines main
and uses dlopen/dlsym
to interact with a plugin dynamically loaded shared library. The host might be a game, and the plugin might be a mod for the game.
Now consider a shared library like SDL that has its own global state that can be manipulated through many functions. Both the host and the plugin need to be able to access this, and manipulate the global state, but they both need to be able to see the exact same state.
An easy but tedious solution which I've been applying so far is passing function pointers from the host into the plugin, and not even linking the shared library into the plugin. This seems like a very safe option to ensure there's no issues, but the problem is I need to manually declare all the function pointers in a struct, and end up with something that looks like this
struct Context {
// ...
void (*DrawCircle)(vec2 position, float radius, struct ColorF32);
void (*DrawCircleOutline)(vec2 position, float radius, struct ColorF32);
void (*DrawRectOutline)(vec2 center, vec2 size, struct ColorF32);
bool (*IsKeyDown)(int);
bool (*IsKeyPressed)(int);
bool (*IsKeyReleased)(int);
bool (*IsMouseButtonDown)(int);
bool (*IsMouseButtonPressed)(int);
bool (*IsMouseButtonReleased)(int);
// ...
}
What I'd like is a solution where I'm able to link the same shared library to both the host and all of my plugins (there can be many), and just include the same header for the shared library in both, and call those functions directly.
What I don't know is how to tell the compiler that when I do gcc host.c -lsdl2
and gcc plugin.c -shared -fPIC -lsdl2
that it should not have its own copies of the global state, but instead resolve all those symbols to the already existing symbols in the host when the plugin is dynamically loaded.
I'm currently using Linux, but it would be preferrable if there was a way to do this that works on all desktop platforms (Windows, Linux, MacOS), but if there is a solution that is significantly easier that works only on Linux I'd like to see that too.
Note that SDL is just an example, there are many more shared libraries I'd like to use this way, and there is more than one plugin that the host loads.
Upvotes: 0
Views: 70