c程序调用c的so动态库

c程序调用c的so动态库


经常遇到这样一个问题,我们需要用程序调用其他人封装好的一个功能库中的函数,即动态库,在linux系统中,这个动态库一般是so后缀结尾的,类似windows的dll库。

今天完成两个小程序,一个是c程序,另外一个是c动态库,并用c程序调用c动态库中的函数。

1、c程序实现

代码实现:

/*******************************************************
* file:testLoadSoFile.c
* date:2021-05-10
* version:1.0.0.1
* author:jack8126
* description: test for read so file
*******************************************************/
#include <stdio.h>
#include <dlfcn.h>  

typedef char* (*printHello)();

// main func
int main(int argc, char **argv)
{
    unsigned char u8SoNameRead[512] = {0}; 
	void *handleFunc = NULL;
	char *error = NULL;
	unsigned char version[64] = {0};

	
	if(argc < 2)
	{
		printf("please input like this:\r\n");
		printf("./testLoadSoFile.bin testHelloLib.so \r\n");
		printf("testHelloLib.so --------------- input file \r\n");
		return -1;
	}
	
    sprintf(u8SoNameRead,"%s",argv[1]);
	printf("u8SoNameRead =%s\r\n\r\n",u8SoNameRead);	

	handleFunc = dlopen(u8SoNameRead, RTLD_LAZY);
	if( !handleFunc) {
		fprintf(stderr, "%s ", dlerror());
		//exit(1);
		return -1;
	}

	printHello pPrintHello = (printHello)dlsym(handleFunc, "printHello");

	printf("read so file before\r\n");
	char* pReturn = pPrintHello();
	printf("pReturn1 =%s\r\n\r\n",pReturn);
	printf("pReturn2 =%s\r\n",pPrintHello());

	return 0;
}


注意使用dlopen函数时,需增加头文件#include <dlfcn.h>

且需要知道so动态库提供的接口printHello。

编译c程序:

gcc testLoadSoFile.c -o testLoadSoFile.bin -ldl

编译时需增加-ldl

在这里插入图片描述

编译之后生成testLoadSoFile.bin文件。

2、c动态库实现

c动态库代码:

/*******************************************************
* file:testHelloLib.c
* date:2021-05-10
* version:1.0.0.1
* author:jack8126
* description: test for so print hello
*******************************************************/
#include <stdio.h>

char *printHello(){
	printf("so hello! \r\n");

	return "success";
}


编译c动态库

gcc testHelloLib.c -o testHelloLib.so -shared -fPIC

编译时需增加-fPIC

在这里插入图片描述

编译之后生成动态库testHelloLib.so。

3、执行程序

执行命令

./testLoadSoFile.bin ./testHelloLib.so 

在这里插入图片描述
看到有打印so hello字段,表示testLoadSoFile.bin文件,已经加载testHelloLib.so文件,并成功调用了其中的函数。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值