C语言 dlopen dlsym

C语言加载动态库

头文件:#include<dlfcn.h>

void * dlopen(const char* pathName, int mode); 返回值 handle 

void *dlsym(void *handle, const char* symbol); 返回值 函数起始地址

 

handle是使用dlopen函数之后返回的句柄,symbol是要求获取的函数的名称,函数,返回值是void*,指向函数的地址;

 

测试:

创建一个.c文件,编译成动态链接库

/*************************************************************************
    > File Name: hello.c
    > Author: 
    > Mail: 
    > Created Time: 2019年12月12日 星期四 14时39分42秒
 ************************************************************************/

#include<stdio.h>

int hello() {
    printf("hello c \n");
    return 0;
}
gcc -shared -fPIC hello.c -o hello.so

创建一个头文件申明hello函数

/*************************************************************************
    > File Name: hello.h
    > Author: 
    > Mail: 
    > Created Time: 2019年12月12日 星期四 14时40分25秒
 ************************************************************************/

#ifndef _HELLO_H
#define _HELLO_H

int hello();
 
#endif

创建一个main.c用于测试编译的hello.so是否正确

/*************************************************************************
    > File Name: mian.c
    > Author: 
    > Mail: 
    > Created Time: 2019年12月12日 星期四 14时41分22秒
 ************************************************************************/

#include<stdio.h>
#include"hello.h"

int main() {
    hello();
    return 0;
}

使用动态链接库编译

gcc main.c -o app ./hello.so

运行编译好的app文件输出如下

hello c

证明动态链接库编译成功,接下来使用dlopen和dlsym调用hello.so内的hello函数

/*************************************************************************
    > File Name: mian.c
    > Author: 
    > Mail: 
    > Created Time: 2019年12月12日 星期四 14时41分22秒
 ************************************************************************/

#include<stdio.h>
#include<dlfcn.h>
#include"hello.h"

typedef int (*callback)();
static callback cb;

int main() {
    void* handle;
    handle = dlopen("./hello.so",RTLD_LAZY);
    if (!handle) {
        printf("handle is  null \n");
        return 0;
    }
    cb = (callback)dlsym(handle, "hello");
    cb();
    return 0;
}

编译main.c 需要链接静态库

gcc main.c -o app -ldl

运行程序

hello c

可以发现与之前使用动态链接库编译运行结果相同。

posted @ 2019-12-12 15:28  Piilu  阅读(1412)  评论(0)    收藏  举报