C++文件中通过动态链接库调用C文件

首先是几个用来加载动态库文件的函数的介绍:

#include 
void *dlopen(const char *filename, int flag);//以指定模式打开指定的动态连接库文件,并返回一个句柄给调用进程    
 指定模式:
    RTLD_LAZY 暂缓决定,等有需要时再解出符号 
RTLD_NOW 立即决定,返回前解除所有未决定的符号。
char *dlerror(void);//返回出现的错误
void *dlsym(void *handle, const char *symbol);//通过句柄和连接符名称获取函数名或者变量名
int dlclose(void *handle);//卸载打开的库
具体步骤:

1.产生动态链接库:例如下为fun.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 d(int a, int b)
{
    return (a/b);
}
编写好此文件后通过:编译参数 gcc -fPIC -shared  将程序fun.c编译为动态链接库fun.so : gcc -fPIC -shared add.c -o add.so

2.用测试函数调用fun.so动态库:例如如下为DynamicTest.cpp文件,内容如下:

#include 
#include 
typedef int (*fun_ptr)(int a,int b);
using namespace std;
int main(int argc, char const *argv[])
{
	void *handler=dlopen("./fun.so",RTLD_LAZY);
	
	if(handler!=NULL)
	{
		fun_ptr fun=(fun_ptr)dlsym(handler,"add");
		cout<
编写好内容后,通过指令:g++ -rdynamic -o DynamicTest DynamicTest.cpp -ldl  调用动态库。生成可执行文件DynamicTest。

3.运行可执行文件指令:./DynamicTest

运行结果:

[root@localhost DynamicLinking]# ./DynamicTest
7
-1
12
2

这只是动态库链接的基础操作,所以关于动态库的原理我还的继续学习。如有出错的地方,欢迎指出。




你可能感兴趣的:(C++)