Created
June 4, 2019 03:45
-
-
Save 410063005/c3582c7e9b8d26e3f4f825576a4bae5d to your computer and use it in GitHub Desktop.
dlsym 示例。so 编译命令 gcc -fPIC -shared op.c -o libop.so
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "op.h" | |
#include <dlfcn.h> | |
#include <stdio.h> | |
typedef int (*CACULATE_FUNC)(int, int); | |
int main(int argc, char* argv[]) | |
{ | |
dlerror(); | |
char* error_msg; | |
void* handle = dlopen("libop.so", RTLD_NOW); | |
if (handle == 0) { | |
printf("load error\n"); | |
return -1; | |
} | |
if ((error_msg = dlerror()) != 0) { | |
printf("error msg %s\n", error_msg); | |
return -1; | |
} | |
printf("load success\n"); | |
void* sym_add = dlsym(handle, "add"); | |
if (sym_add == 0) { | |
printf("dlsym error\n"); | |
if ((error_msg = dlerror()) != 0) { | |
printf("error msg %s\n", error_msg); | |
return -1; | |
} | |
return -1; | |
} | |
void* sym_mul= dlsym(handle, "mul"); | |
if (sym_mul == 0) { | |
printf("dlsym error\n"); | |
if ((error_msg = dlerror()) != 0) { | |
printf("error msg %s\n", error_msg); | |
return -1; | |
} | |
return -1; | |
} | |
CACULATE_FUNC add_func = sym_add; | |
CACULATE_FUNC mul_func = sym_mul; | |
printf("%d + %d = %d\n", 1, 11, add_func(11, 1)); | |
printf("%d x %d = %d\n", 10, 10, mul_func(10, 10)); | |
dlclose(handle); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "op.h" | |
int add(int i, int j) | |
{ | |
return i + j; | |
} | |
int mul(int i, int j) | |
{ | |
return i * j; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int add(int i, int j); | |
int mul(int i, int j); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment