Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cross-platform method of accessing functions within shared objects/libraries.
#include <stdio.h>
#include <string.h>
/* Preprocessor Macros */
#ifdef _WIN32
#include <windows.h>
#define EXTENSION ".dll"
#define OPENLIB(a) LoadLibrary(a)
#define CALLFUNC(a, b) GetProcAddress(a, b)
#define CLOSELIB(a) FreeLibrary(a)
#else
#include <dlfcn.h>
#define EXTENSION ".so"
#define OPENLIB(a) dlopen(a, RTLD_LAZY)
#define CALLFUNC(a, b) dlsym(a, b)
#define CLOSELIB(a) dlclose(a)
#endif
static void *OpenLibrary(const char *filename, const char *function) {
char filename_with_extension[strlen(filename) + strlen(EXTENSION) + 1];
sprintf(filename_with_extension, "%s%s", filename, EXTENSION);
fprintf(stdout, "[INFO] Loading shared library: %s\n", filename_with_extension);
void *handle = OPENLIB(filename_with_extension);
if (handle) {
void *f = CALLFUNC(handle, function);
if (!f) {
fprintf(stderr, "[ERROR] Failed to call function: %s\n", function);
CLOSELIB(handle);
return NULL;
}
fprintf(stdout, "[INFO] Successfully called function: %s\n", function);
return f;
}
fprintf(stderr, "[ERROR] Failed to load library: %s\n", filename_with_extension);
return NULL;
}
typedef int (*func)(int, int);
int main(int argc, char **argv) {
func f = (func) OpenLibrary("test", "add");
fprintf(stdout, "[RUN] %d\n", f(10, 15));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.