Add portable layer for dynamic loading
[emacs.git] / src / dynlib.c
blobf9478099169a171a8b38cf411eb4773924dd2b66
1 /*
2 * Portable API for dynamic loading
4 * Assuming modules are enabled on modern systems... *Yes*, the
5 * preprocessor macro checks could be more precise. I don't care.
7 * If you think the abstraction is too leaky use libltdl (libtool),
8 * don't reinvent the wheel by fixing this one.
9 */
11 #include "dynlib.h"
14 * Windows systems
16 #if defined(_WIN32)
18 #include <windows.h>
20 dynlib_handle_ptr dynlib_open (const char * path)
23 return (dynlib_handle_ptr) LoadLibrary (path);
26 void * dynlib_sym (dynlib_handle_ptr h, const char * sym)
28 return GetProcAddress ((HMODULE) h, sym);
31 bool dynlib_addr (void *ptr, const char **path, const char **sym)
33 return false; /* not implemented */
36 const char * dynlib_error (void)
38 /* TODO: use GetLastError(), FormatMessage(), ... */
39 return "Can't load DLL";
42 int dynlib_close (dynlib_handle_ptr h)
44 return FreeLibrary ((HMODULE) h) != 0;
49 * POSIX systems
51 #elif defined(HAVE_UNISTD_H)
53 #include <dlfcn.h>
55 dynlib_handle_ptr dynlib_open (const char * path)
57 return dlopen (path, RTLD_LAZY);
60 void * dynlib_sym (dynlib_handle_ptr h, const char * sym)
62 return dlsym (h, sym);
65 bool dynlib_addr (void *ptr, const char **path, const char **sym)
67 #ifdef HAVE_DLADDR
68 Dl_info info;
69 if (dladdr (ptr, &info) != 0 && info.dli_fname != NULL && info.dli_sname != NULL)
71 *path = info.dli_fname;
72 *sym = info.dli_sname;
73 return true;
75 #endif
76 return false;
79 const char * dynlib_error (void)
81 return dlerror ();
84 int dynlib_close (dynlib_handle_ptr h)
86 return dlclose (h) == 0;
89 #else
91 #error "No dynamic loading for this system"
93 #endif