The dl Library, Part 2

By Danny Kalev, ITworld |  How-to

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
handle.

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 greetings.so 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 greetings.so file is located at /usr/lib */

#include
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 greetings.so file at /usr/lib. Now we want to use this shared
library in another program that uses the dl interface. Our program
opens the greetings.so 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("greetings.so",RTLD_LAZY);
if(lib==NULL)
{
printf("failed to open gretings.so: %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.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question