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?
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <dlfcn.h>
4
​
5
int main(int argc, char **argv)
6
{
7
void *handle;
8
9
// An function pointer, for point to test_foo
10
int (*test_foo_pointer)(float);
11
char *error;
12
​
13
//open the target library libtest.so
14
handle = dlopen("libtest.so", RTLD_LAZY);
15
if (!handle) {
16
fprintf(stderr, "%s\n", dlerror());
17
exit(EXIT_FAILURE);
18
}
19
​
20
dlerror(); // Clear any existing error
21
​
22
​
23
// get test_foo and assign to test_foo_pointer
24
test_foo_pointer = dlsym(handle, "test_foo");
25
26
if ((error = dlerror()) != NULL) {
27
fprintf(stderr, "%s\n", error);
28
exit(EXIT_FAILURE);
29
}
30
​
31
dlclose(handle);
32
exit(EXIT_SUCCESS);
33
}
Copied!
Copy link