1.Declare a pointer to a data structure of the same type as the data structure to access in the library
2.Using shl_findsym with the type parameter set to TYPE_DATA, find the symbol in the shared library and assign its address to the pointer declared in Step 1
3.Access the data through the pointer obtained in Step 2
shl_findsym Example
Suppose you have a set of libraries that output to various graphics devices. Each graphics device has its own library. Although the actual code in each library varies, the routines in these shared libraries have the same name and parameters, and the global data is the same. For instance, they all have these routines and data:
gopen() | opens the graphics device for output | |
gclose() | closes the graphics device | |
|
| |
move2d(x,y) | moves to pixel location x,y | |
|
| |
draw2d(x,y) | draws to pixel location x,y from current x,y | |
|
|
|
maxX | contains the maximum | X pixel location on the output device |
|
|
|
maxY | contains the maximum | Y pixel location on the output device |
|
|
|
The following example shows a C program that can load any supported graphics library at run time, and call the routines and access data in the library. The program calls load_lib (see “shl_load Example” (page 170) ) to load the library.
Load a Shared Library and Call its Routines and Access its Data
#include <stdio.h> | /* contains standard I/O defs | */ |
#include <stdlib.h> | /* contains getenv definition | */ |
#include <dl.h> | /* contains shared library type defs */ | |
/* |
|
|
*Define linker symbols:
*/
#define | GOPEN | "gopen" |
|
|
#define | GCLOSE | "gclose" |
|
|
#define | MOVE2D | "move2d" |
|
|
#define | DRAW2D | "draw2d" |
|
|
#define | MAXX | "maxX" |
|
|
#define | MAXY | "maxY" |
|
|
shl_t | load_lib(int argc, char * argv[]); |
| ||
main(int argc, |
|
|
| |
char * argv[]) |
|
| ||
{ |
|
|
|
|
shl_t lib_handle; | /* handle of shared library | */ | ||
int | (*gopen)(void); | /* opens the graphics device | */ | |
int | (*gclose)(void); | /* closes the graphics device | */ | |
int | (*move2d)(int, int); | /* moves to specified x,y location */ | ||
int | (*draw2d)(int, int); | /* draw line to specified x,y location*/ | ||
int | *maxX; |
| /* maximum X pixel on device | */ |
int | *maxY; |
| /* maximum Y pixel on device | */ |
lib_handle = load_lib(argc, | argv); /* load required shared library */ | |||
/* |
|
|
|
|
*Get addresses of all functions and data that will be used:
*/
if (shl_findsym(&lib_handle, GOPEN, TYPE_PROCEDURE, (void *) &gopen)) perror("shl_findsym: error finding function gopen"), exit(1);
if (shl_findsym(&lib_handle, GCLOSE, TYPE_PROCEDURE, (void *) &gclose)) perror("shl_findsym: error finding function gclose"), exit(1);
if (shl_findsym(&lib_handle, MOVE2D, TYPE_PROCEDURE, (void *) &move2d)) perror("shl_findsym: error finding function move2d"), exit(1);
174 Shared Library Management Routines