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文件,并成功调用了其中的函数。