pelib  2.0.0
src/dl.cpp
Go to the documentation of this file.
00001 /*
00002  Copyright 2015 Nicolas Melot
00003 
00004  This file is part of Pelib.
00005 
00006  Pelib is free software: you can redistribute it and/or modify
00007  it under the terms of the GNU General Public License as published by
00008  the Free Software Foundation, either version 3 of the License, or
00009  (at your option) any later version.
00010 
00011  Pelib is distributed in the hope that it will be useful,
00012  but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
00014  GNU General Public License for more details.
00015 
00016  You should have received a copy of the GNU General Public License
00017  along with Pelib. If not, see <http://www.gnu.org/licenses/>.
00018 */
00019 
00020 
00021 #include <stdlib.h>
00022 #include <dlfcn.h>
00023 #include <stdio.h>
00024 
00025 #include <pelib/dl.h>
00026 
00027 void*
00028 load_lib(const char* library)
00029 {
00030         void *handle;
00031         char *error;
00032 
00033         handle = dlopen(library, RTLD_LAZY);
00034         if (!handle) {
00035                 fprintf(stderr, "[%s:%s:%d] Cannot open shared library: %s\n", __FILE__, __FUNCTION__, __LINE__, dlerror());
00036                 exit(EXIT_FAILURE);
00037         }
00038 
00039         if ((error = dlerror()) != NULL)  {
00040                 fprintf(stderr, "[%s:%s:%d] Error while opening shared library: %s\n", __FILE__, __FUNCTION__, __LINE__, error);
00041                 exit(EXIT_FAILURE);
00042         }   
00043 
00044         return handle;
00045 }
00046 
00047 void*
00048 load_function(void *handle, const char *function)
00049 {
00050         dlerror();    /* Clear any existing error */
00051 
00052         void *func = (void*)dlsym(handle, function);
00053         char *error;
00054 
00055         if ((error = dlerror()) != NULL)  {
00056                 fprintf(stderr, "[%s:%s:%d] Error while loading function: %s\n", __FILE__, __FUNCTION__, __LINE__, error);
00057                 exit(EXIT_FAILURE);
00058         }   
00059 
00060         return func;
00061 }
00062 
00063 void
00064 destroy_lib(void *handle)
00065 {
00066         dlclose(handle);
00067 }
00068