JNI加载hal的dlopen()相关操作

1.函数集合

#include <dlfcn.h>

void *dlopen(const char *filename, int flag);
char *dlerror(void);
void *dlsym(void *handle, const char *symbol);
int dlclose(void *handle);

Link with
-ldl.

2.Demo例子

caculate.c用于编译成一个库

int add(int a,int b)
{
    return (a + b);
}

int sub(int a, int b)
{
    return (a - b);
}

int mul(int a, int b)
{
    return (a * b);
}

int div(int a, int b)
{
    return (a / b);
}
View Code

main.c调用这个库里面的函数

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>


#define LIB_CACULATE_PATH "./libcaculate.so"

typedef int (*CAC_FUNC)(int, int);

int main()
{
    void *handle;
    char *error;
    CAC_FUNC cac_func = NULL;

    handle = dlopen(LIB_CACULATE_PATH, RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s
", dlerror());
        return -1;
    }

    //获取一个函数
    cac_func = dlsym(handle, "add");
    if ((error = dlerror()) != NULL)  {
        fprintf(stderr, "%s
", error);
        return -1;
    }
    printf("add: 2+7=%d
", cac_func(2,7));

    cac_func = dlsym(handle, "sub");
    printf("sub: 9-2=%d
", cac_func(9,2));

    cac_func = dlsym(handle, "mul");
    printf("mul: 3*2=%d
", cac_func(3,2));

    cac_func = dlsym(handle, "div");
    printf("div: 8/2=%d
", cac_func(8,2));

    dlclose(handle);

    return 0;
}
View Code

编译执行:

编译:
$ gcc -rdynamic -o main main.c -ldl
$ gcc -shared -fPIC caculate.c -o libcaculate.so
执行:
$ ./main 
add: 2+7=9
sub: 9-2=7
mul: 3*2=6
div: 8/2=4
View Code

或者使用一个结构体将所有的函数包装起来,这样只需要调用一次dlsym()

struct math {
    int (*add)(int a,int b);
    int (*sub)(int a,int b);
    int (*mul)(int a,int b);
    int (*div)(int a,int b);
};

static int math_add(int a,int b)
{
    return (a + b);
}

static int math_sub(int a, int b)
{
    return (a - b);
}

static int math_mul(int a, int b)
{
    return (a * b);
}

static int math_div(int a, int b)
{
    return (a / b);
}

/*shouldn't be static, else dlsym() couldn't find it*/
struct math HMI = {
    .add = math_add,
    .sub = math_sub,
    .mul = math_mul,
    .div = math_div,
};
View Code
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

struct math {
    int (*add)(int a,int b);
    int (*sub)(int a,int b);
    int (*mul)(int a,int b);
    int (*div)(int a,int b);
};

#define LIB_CACULATE_PATH "./libcaculate.so"

typedef int (*CAC_FUNC)(int, int);

int main()
{
    void *handle;
    char *error;
    struct math *hmi;

    handle = dlopen(LIB_CACULATE_PATH, RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s
", dlerror());
        return -1;
    }

    //获取一个函数
    hmi = dlsym(handle, "HMI");
    if ((error = dlerror()) != NULL)  {
        fprintf(stderr, "%s
", dlerror());
        return -1;
    }
    printf("add: 2+7=%d
", hmi->add(2,7));
    printf("sub: 9-2=%d
", hmi->sub(9,2));
    printf("mul: 3*2=%d
", hmi->mul(3,2));
    printf("div: 8/2=%d
", hmi->div(8,2));

    dlclose(handle);

    return 0;
}
View Code

3.详细信息:# man dlopen

原文地址:https://www.cnblogs.com/hellokitty2/p/10790200.html