Sunday, February 08, 2009

Dynamic Load Library - Linux

Have you ever wondered, how to load, link and execute library functions when it is needed and unload it after it is used in Linux.

libdl - Library gives you this opportunity. For example:

* If you are writing an application which makes use of XML Parsing Library sparingly. You may want to load this XML Library when there is need and unload it afterwards.
* Or, you may want to load choose a particular library depending on the runtime parameters of an application.

libdl comes in handy, with only 3 interfaces with in the library. The following functions are defined in "dlfcn.h".

* dlopen - gain access to an executable object file
* dlsym - obtain the address of a symbol from a dlopen object
* dlclose - close a dlopen object
* dlerror - dlerror - get diagnostic information

void *handle;
int *iptr, (*fptr)(int);

/* open the needed object */
handle = dlopen("/usr/home/me/libfoo.so", RTLD_LOCAL | RTLD_LAZY);

/* find the address of function and data objects */
*(void **)(&fptr) = dlsym(handle, "my_function");
iptr = (int *)dlsym(handle, "my_object");

/* invoke function, passing value of integer as a parameter */
(*fptr)(*iptr);



Don't forget to set the LD_LIBRARY_PATH.

5 comments:

Unknown said...

thala neenge range thala :-) Vayasu aaga aaga engeyo poringe !

Reemus Kumar said...

Anna Sai Kiran, ungalukku enna vayaso athey vasayithan ennakum.

You must read "Ageless Mind, Timeless Body" by Deepak Chopra.

Unknown said...

c++ padikave time kedekamatengudhu idhula body/mind nu aged people ela budhimathi solringe :-)

its ok padikiren na epome periyavinga pechu keppen !

Anonymous said...

Thanks, this was exactly what I was looking for! I've never done dynamic loading manually before, but it looks pretty simple from what you've shown.

What is LD_LIBRARY_PATH used for, though? For loading libraries referenced by the one you specified? If libfoo.so refers to libbar.so in the same directory, will libbar.so be found without having it in LD_LIBRARY_PATH?

Anonymous said...
This comment has been removed by a blog administrator.