linux 动态加载动态库

来源:互联网 发布:运动香水知乎 编辑:程序博客网 时间:2024/04/30 12:47

linux 动态加载动态库  

动态加载库

在Linux中可以动态加载库,其使用方法如下:

1. 先生成一个动态库libtest.so

/* test.c */

#include <stdio.h>

#include <stdio.h>

void test1(int no)

{

    printf("*****************************************\n");

    printf("This is test1, the number is %d.\n", no);

    printf("*****************************************\n");

}

void test2(char *str)

{

    printf("=========================================\n");

    printf("This is test2, the string is %s.\n", str);

    printf("=========================================\n");

}

编译库:

gcc -fPIC -shared -o libtest.so test.c

这样就可以生成libtest.so动态库。

在这个库里,定义个两个函数test1,test2,下面将在程序中加载libtest.so,然后调用test1,test2。

2. 动态加载libtest.so

/* main.c */

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <dlfcn.h> /* 必须加这个头文件 */

#include <assert.h>

int main()

{

    void *handler = dlopen("libtest.so", RTLD_NOW);

    assert(handler != NULL);

    void (*test1)(int) = dlsym(handler, "test1");

    assert(test1 != NULL);

    void (*test2)(char *) = dlsym(handler, "test2");

    assert(test2 != NULL);

    (*test1)(10);

    (*test2)("hello");

    dlclose(handler);

    return 0;

}

/* end */

在这个程序中,dlopen函数用来打开一个动态库,其返回一个void *的指针,如果失败,返回NULL。

dlsym返回一个动态库中的一个函数指针,如果失败,返回NULL。

dlclose关闭指向动态库的指针。

编译的时候需要加上 -ldl

gcc -o main main.c -ldl

运行main,将会看到调用test1,和test2的结果。

原创粉丝点击