Comment on page
Use dlopen and dlsym to get handler of dynamic library(.so)
If you have a dynamic library (libtest.so) and there is a function (int test_foo(float)) in this library, how can I reuse the function in another library?
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv)
{
void *handle;
// An function pointer, for point to test_foo
int (*test_foo_pointer)(float);
char *error;
//open the target library libtest.so
handle = dlopen("libtest.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror(); // Clear any existing error
// get test_foo and assign to test_foo_pointer
test_foo_pointer = dlsym(handle, "test_foo");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
dlclose(handle);
exit(EXIT_SUCCESS);
}
Last modified 2yr ago