In a previous article I explained how to create a shared library (in Mac OS X) and how to build an application using this shared library.


Instead of linking the application against the library, the developer can choose to manually load the shared library.

This procedure is good enough if the developer wants to control the linking of the library himself. To do this job you have to use the "dl" interface. So, the developer first needs to open a handle to that library, and then he needs to retrieve function pointers from the shared library.

library

Starting from the source code of the previous article, we are going to modify only the main program and then we are going to compile it 


The main.c becomes the following one:

 

 

#include "helloworld.h"

#include <dlfcn.h>

#include <stdio.h>

#include <stdlib.h>



int main(int argc, char **argv)

{

    void *lib_handle;

    int (*hello_func)();

    lib_handle = dlopen("libhello.dylib",RTLD_NOW);

    if(lib_handle==NULL) {

        /* Manage errors */

    }

    hello_func = (int (*)()) dlsym(lib_handle,"printHelloWorld");

    if(hello_func==NULL) {

        /* Manage errors */

    }

    (*hello_func)();

    exit(EXIT_SUCCESS);

}


 

 


In the include section I've added the dlfcn.h header file since I have to use the dl* functions. The I've defined the pointer to the function I want to use. With the dlopen call I open the library and last with the dlsym call I've assigned to the hello_func pointer the function I want to use (the address).
To call the function just call the function pointer as shown before the exit statement.
 

Gg1