open a shared library at runtime, find a symbol, call it
open a shared library at runtime, find a symbol, call it
- Author
- Castagnier Mickael
- Version
- 1.0
- Date
- 24/09/2026
Opens the system maths library (kernel32 on Windows), finds a function in it and calls it, then checks the failures: a library that is not there, a symbol the library does not have, and closing twice. Each failure must leave a reason in n_module_error().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if defined(__windows__)
#define EX_LIBRARY "kernel32.dll"
#define EX_SYMBOL "GetTickCount"
#elif defined(__APPLE__)
#define EX_LIBRARY "libSystem.dylib"
#define EX_SYMBOL "cos"
#else
#define EX_LIBRARY "libm.so.6"
#define EX_SYMBOL "cos"
#endif
if (!ok) {
} else {
}
}
int opt = 0;
while ((opt = getopt(argc, argv, "V:")) != -1) {
if (opt == 'V') {
} else {
return -1;
}
}
return 0;
}
int main(
int argc,
char** argv) {
void* symbol = NULL;
fprintf(stderr, "usage: %s [-V LOGLEVEL]\n", argv[0]);
return 2;
}
module = n_module_open(EX_LIBRARY);
expect_true(
"the system library opens", module != NULL);
if (module) {
#if !defined(__windows__)
if (symbol) {
double (*fn)(double) = NULL;
memcpy((void*)&fn, (const void*)&symbol, sizeof(fn));
expect_true(
"calling it gives cos(0) = 1", fn(0.0) == 1.0);
}
#endif
expect_true(
"close sets the handle to NULL", module == NULL);
}
module = n_module_open("n_module_no_such_library.so");
expect_true(
"a missing library is NULL", module == NULL);
return 1;
}
return 0;
}
static void expect_true(const char *label, int cond)
#define EX_SYMBOL
a function whose answer is known
static int parse_args(int argc, char **argv)
read -V LOGLEVEL
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
#define LOG_ERR
error conditions
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL ).
#define LOG_NOTICE
normal but significant condition
#define LOG_INFO
informational
const char * n_module_extension(void)
The file extension shared libraries have on this platform.
int n_module_close(N_MODULE **module)
Close a library and free its handle.
void * n_module_symbol(N_MODULE *module, const char *name)
Find a symbol in an opened library.
const char * n_module_error(void)
What the system said about this thread's last failed call.
Common headers and low-level functions & define.
Load a shared library at runtime and find its symbols.