views:

152

answers:

4

Hi, everyone.

Working in C, on top of unix, I am loading and using a shared library somewhat as follows:

...

handle = dlopen("nameOfLib");

...

libInit();

...

libGoToState1();


libGoToState2();


....

libTerminate();

...

dlclose(handle);

...

What I would like is for my application to admit 'plugins' which take the form of dynamically loadable libraries that adhere to a given API.

The tricky part is that I want to load a plugin after calling libInit() and I want the plugin to be able to call libGoToSomeOtherState(), altering the state of the library, but making use of the same 'session' as the application that loaded it.

Any thoughts on how I need to go about coding this are appreciated.

Specifically, what needs to go into the .c files for the plugin and the main program in order for them to share a library instance, state and all?

+2  A: 

I'm not sure if this is exactly what you're looking for, but an article on how to create simple plugins for C programs was posted on reddit a few days ago:

http://thisxorthat.blogspot.com/2010/01/choose-indecision-simple-plugins-in-c.html

Dana
+1 for that interesting blog! Cheers! :)
tommieb75
+1  A: 

The standard way to export an interface to be used by a plugin is to either put that interface itself into a shared library that the plugin links to, or else pass the plugin a structure of function pointers (in libInit(), presumably) that it then uses to do its work.

Andy Ross
A: 

As a brief hint I'd suggest using callbacks: either passing the library handle to the plugin, or use function pointers inside the plugin to call the original library functions.

lorenzog
+1  A: 

The plugin can call dlsym(RTLD_DEFAULT, "libGoToSomeOtherState") to obtain the address of the function it wants to call, or you can directly pass that function pointer to the plugin's init routine (perhaps within a table of such function pointers).

caf