dave mankoff
dave mankoff

Reputation: 17779

Dynamically Loading External Modules in a C Program?

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?

Upvotes: 3

Views: 655

Answers (3)

unwind
unwind

Reputation: 399871

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.

Upvotes: 3

Robert Gamble
Robert Gamble

Reputation: 109062

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.

Upvotes: 4

Mike F
Mike F

Reputation:

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.

Upvotes: 6

Related Questions