linux c之动态打开链接库(dlopen dlsym dlclose)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011068702/article/details/82468700

1 linux提供了加载和处理动态链接库的系统调用

2 主要函数

1) dlopen、
    dlopen以指定模式打开指定的动态连接库文件,并返回一个句柄给调用进程,打开模式如下:
RTLD_LAZY 暂缓决定,等有需要时再解出符号
RTLD_NOW 立即决定,返回前解除所有未决定的符号。

 2) dlsym、
    dlsym通过句柄和连接符名称获取函数名或者变量名

3) dlclose
    dlclose来卸载打开的库

4) dlerror
    dlerror返回出现的错误

3 测试Demo

  1)写一个add.c文件,然后编译成一个libadd.so,add.c文件如下

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

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

编译参数 gcc -fPIC -shared
编译命令

gcc -fPIC -shared add.c -o libadd.so

我们把生成的so拷贝到我们需要测试的test.c同一个目录下
test.c文件如下

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

# define PATH "./libadd.so"

typedef int(*Fun)(int, int);

int main()
{
	void  *handle;
	char *error;
	Fun fun = NULL;
	//open so
	handle = dlopen(PATH, RTLD_LAZY);
	if (!handle)
	{
		printf("open error\n");
		exit(EXIT_FAILURE);
	}
	puts("open success");
	//clear before errror
	dlerror();
	//get the method of add
	fun = (Fun)dlsym(handle, "add");
	if ((error = dlerror()) != NULL)
	{
		printf("dlsym error\n");
		exit(EXIT_FAILURE);
	}
	printf("dlsym success\n");
	printf("5 + 5 is %d\n", fun(5, 5));
	fun = (Fun)dlsym(handle, "sub");
	printf("10 - 5 is %d\n", fun(10, 5));
	//close 
	dlclose(handle);
	return 0;	
}

4 运行结果

我们编译test.c文件的时候要记得加上-ldl

gcc -g test.c -o test -ldl

结果如下

open success
dlsym success
5 + 5 is 10
10 -5 is 5

猜你喜欢

转载自blog.csdn.net/u011068702/article/details/82468700
今日推荐