The dl Library, Part 2

This week, I will continue discussing the dl library and exemplify its

usage. Before we start though, I'll quickly overview the dl functions

presented last week:

const char * dlerror(void);

dlerror() returns a string describing the error that occurred. If

no error occurred, then it returns NULL.

void * dlopen(const char * filename, int flags)

The dlopen() function opens a library and returns a matching


void* dlsym(void * libhandle, char * symbol);

dlsym() searches for a symbol within a library.

void * dlclose(void * libhandle);

dlclose() unloads, or closes, a library that was previously opened

using dlopen().

A Complete Program

Suppose you have a shared library called that you compiled

and installed in the /usr/lib directory. For the sake of brevity, let's

assume that the greetings library has only one function: goodday(). The

greetings.c file looks as follows:

/*greetings.c - implementation of the greetings shared library. The

resulting file is located at /usr/lib */


void goodday(void) { printf("have a good day\n"); } The greetings.h header looks like this: /*greetings.h -- declares the goodday() function of the greetings.c library*/ #ifndef GREETING_H_INCLUDED #define GREETING_H_INCLUDED void goodday(void); #endif Let's assume that we already compiled greetings.c and installed the resulting file at /usr/lib. Now we want to use this shared library in another program that uses the dl interface. Our program opens the library, locates the function goodday(), calls it using the pointer returned from dlsym(), and closes the library. I included below two technical notes that refer to the comments numbered 1 and 2. #include #include #include #include "greetings.h" int main() { void* lib; void (*pgoodday)(void); /*pointer to function*/ const char *errmsg; lib=dlopen("",RTLD_LAZY); if(lib==NULL) { printf("failed to open %s", dlerror()); exit(-1); } dlerror(); /*clear before calling dlopen()*/ pgoodday=dlsym(lib, "goodday"); /*locate function's address*/ errmsg=dlerror(); /* #2 check whether dlsym succeeded*/ if(errmsg) { printf("failed to locate goodday(): %s", dlerror()); exit(-1); } goodday(); /* #2 call library's function through the pointer obtained previously*/ dlclose(lib); return 0; } Technical Notes 1. In this case, there's no need to call dlerror() to check whether dlsym() succeeded. Instead, we could have examined the value of pgoodday. Because functions' addresses are never NULL, a NULL value would have indicated a failure. However, I wanted to demonstrate the use of this technique. 2. When you call a function through a pointer, you use the pointer as if it were the function's name. However, the following form is also legal, albeit antiquated and perhaps less readable: (*goodday)();.
Top 10 Hot Internet of Things Startups
Join the discussion
Be the first to comment on this article. Our Commenting Policies