Skip to content

Instantly share code, notes, and snippets.

@410063005
Created June 4, 2019 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 410063005/c3582c7e9b8d26e3f4f825576a4bae5d to your computer and use it in GitHub Desktop.
Save 410063005/c3582c7e9b8d26e3f4f825576a4bae5d to your computer and use it in GitHub Desktop.
dlsym 示例。so 编译命令 gcc -fPIC -shared op.c -o libop.so
#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;
}
#include "op.h"
int add(int i, int j)
{
return i + j;
}
int mul(int i, int j)
{
return i * j;
}
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