/*main.c*/
#include <dlfcn.h>// 相关函数头文件
#include <stdio.h>
int main(void)
{
const char *src = "Hello Dymatic";
int (*pStrLen)(const char *);// 函数指针
void *pHandle = NULL;// 库指针
char *pErr = NULL;// 错误指针
// 打开动态链接库并检查是否有错误发生
pHandle = dlopen("./libstr.so“, RTLD_LASY);
pErr = dlerror();
if(!pHandle || pErr != NULL){printf("Failed load library!\n%s\n", pErr);return -1;}
// 获取StrLen函数地址并检查是否有错误发生
pStrLen = dlsym(pHandle, "StrLen");
pErr = dlerror();
if(!pStrLen || pErr == NULL){printf("%s\n", pErr);return -1;}
// 调用StrLen函数
printf("The string length is:%d\n", pStrLen(src));
// 关闭库文件
dlclose(pHandle);
return 0;
]
运行以下命令编译成可执行文件。-L./ 当前目录,-lstr为StrLen函数所在库文件,-ldl为dlopen等相关函数所在库文件
gcc -o test main.c -L./ -lstr -ldl
原文:https://www.cnblogs.com/LandyTan/p/12029961.html