note
相关系统调用接口:dlopen\dlclose\dlerror\dlsym
code
math.c
int add(int x, int y) {
return (x+y);
}
int sub(int x, int y) {
return (x-y);
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char** argv) {
void* handle = NULL;
int x = 22;
int y = 33;
handle = dlopen(argv[1], RTLD_NOW);
if (handle == NULL) {
printf("dll load error\n");
printf("%s\n", dlerror());
fflush(stdout);
exit(1);
}
printf("dll load success\n");
void* f = dlsym(handle, "add");
if (f == NULL) {
printf("dlsym return NULL\n");
printf("%s\n", dlerror());
fflush(stdout);
dlclose(handle);
exit(1);
}
int (*fun)(int,int) = f;
printf("%d+%d=%d\n", x,y,fun(x,y));
fflush(stdout);
dlclose(handle);
exit(0);
}
makefile
default:
gcc -c math.c -o math.o
gcc -shared -fPIC -o libmath.so math.o
export LD_LIBRARY_PATH=.
gcc main.c -L. -o main.exe -ldl -lmath
test