/* pluginlib.c - functions needed to access plugin functions held in
                 a dynamically loaded library.

   environ - C programming support functions
   Copyright (C) 2005  Martin C Gregorie
   
   This program is free software; you can redistribute it and/or
   modify it under the terms of the Lesser GNU General Public License.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
  
   You should have received a copy of the Lesser GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  
   Contact Martin Gregorie at martin@gregorie.org
*/

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <environ.h>

char *errmsg = NULL;

/*
   Open the dynamic loader library <i>libname</i>.
   On success, return a handle for the library.
   On error, save the error text for retrieval by <i>pluginlib_error()</i>
   and return NULL.
*/
void *pluginlib_open(char *libname)
{
   void *handle = NULL;
   
   errmsg = dlerror();    /* Clear any existing error */
   handle = dlopen(libname, RTLD_LAZY);
   if (!handle)
      errmsg = dlerror();

   return(handle);
}

/*
   Close the plugin library if it was open.
*/
void pluginlib_close(void *handle)
{
   if (handle)
      dlclose(handle);
}   

/*
   Return a pointer to a plugin from the library pointed to
   by <i>*handle</i>.
   
   If the plugin can't be found, save the error text
   for retrieval by <i>pluginlib_error</i> and return NULL. 
*/
void *plugin_getref(void *handle, char *name)
{
   void *ref = NULL;
   ref = dlsym(handle, name);
   if (!ref)
      errmsg = dlerror();

   return ref;
}

/*
   Return a pointer to the error text if an error has ocurred
   and NULL otherwise.
*/
char* pluginlib_error()
{
   return errmsg;
}
