Wednesday, December 07, 2005

Writing a program plugin in C++

Today I found myself trying to imagine how to call a function (or more in general to load a library) at runtime. I know shared object, also called DLL on windows world, can be useful for this, but I never wrote a program that uses dynamic linking.

To do so, I read something about dlfcn.h, a standard library for loading shared object at runtime. Let's see how to use it.

At first, create the shared object:

----hello.cpp----

#include <iostream>

using namespace std;

extern "C" void hello()
{
    cout << "hello world!" << endl;
}


compile it as a shared object:

$ g++ hello.cpp -o hello.so -shared


now create the main program file:

----main.cpp----

#include <iostream>
#include <dlfcn.h>

using namespace std;

int main( int argc, char *argv[] )
{
    void * handle = dlopen( "./hello.so", RTLD_LAZY );

    if( !handle )
    {
        cerr << "Cannot open library: " << dlerror() << endl;
        return 1;
    }

    typedef void (*hello_t)();

    hello_t hello = (hello_t) dlsym(handle, "hello");

    if( !hello )
    {
        cerr << "Cannot load symbol 'hello': " << dlerror() << endl;
        dlclose(handle);
        return 1;
    }

    hello();

    dlclose( handle );

    return 0;
}


compile it as usual:

$ g++ main.cpp -o main -ldl


now we have a shared object, hello.so with hello() function compiled inside it. We also have the main program.
The (almost) obvious output will be:

$ ./main
hello world!


source:
http://www.tldp.org/HOWTO/C++-dlopen/index.html

more informations:
http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html

0 Comments:

Post a Comment

<< Home