Skip to content

Instantly share code, notes, and snippets.

@wilhelmtell
Created March 29, 2010 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilhelmtell/347445 to your computer and use it in GitHub Desktop.
Save wilhelmtell/347445 to your computer and use it in GitHub Desktop.
Dynamically load and invoke a function in C++
///////////////////////////////////////////////////////////////////////////////
// dyn.cc - compiled and linked as a dynamic library
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
extern "C" void fun()
{
std::cout << "BOOYA!!1! fun() invoked!\n";
}
///////////////////////////////////////////////////////////////////////////////
// play.cc - compiled and linked as a regular binary, separately from dyn.cc
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <dlfcn.h>
using namespace std;
int main(int argc, char* argv[])
{
const char* const DYLIB = "libdyn.dylib" /* or .so or .dll or ... */
const char* const SYM = "fun";
cout << "Loading library " << DYLIB << " ..." << endl;
void* handle = dlopen(DYLIB, RTLD_NOW);
if( !handle ) {
cerr << "Error loading library: " << dlerror() << endl;
return -1;
}
cout << "Loading symbol " << SYM << " ..." << endl;
dlerror(); // clear any error
void* ret_sym = dlsym(handle, SYM);
if( ! ret_sym ) {
cerr << "Error loading symbol: " << dlerror() << endl;
dlclose(handle);
return -1;
} else {
typedef void (*fun_t)();
fun_t fun = (fun_t)ret_sym;
cout << "Calling " << SYM << "() ..." << endl;
fun();
}
dlclose(handle);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment