views:

223

answers:

3

I'm sure this problem has been solved before and I'm curious how its done. I have code in which, when run, I want to scan the contents of a directory and load in functionality.

Specifically, I am working with a scripting engine that I want to be able to add function calls to. I want the core engine to provide very limited functionality. The user should be able to add additional functions through 3rd party libraries, which I want the engine to scan for and load. How is this done?

+5  A: 

It depends on the platform. On win32, you call LoadLibrary to load a DLL, then get functions from it with GetProcAddress. On Unixy platforms, the equivalents are dlopen and dlsym.

+4  A: 

You can use the POSIX dlopen/dlsym/dlerror/dlclose functions in Linux/UNIX to dynamically open shared libraries and access the symbols (including functions) they provide, see the man page for details.

Robert Gamble
You can find many examples in existing programs. Shameless plug: my program echoping http://echoping.sourceforge.net/ is a relatively simple exemple of such an use of dlopen().
bortzmeyer
+3  A: 

If you want to use a library for this, I'd recommend GLib (the utility library that lies underneath the GTK+ UI toolkit). It features the "GModule" sub-API, which provides a clean, portable way of doing this. This saves you from having to wrap the relevant calls yourself, and also brings you the rest of GLib which is very handy to have in C programs of any size.

unwind