参考:https://www.cnblogs.com/Anker/p/3746802.html
gcc -fPIC -shared calc.c -o libcalc.so, 编译得到
在linux上 man dlopen可以得到以下信息:
头文件注释:
实践内容:
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h> //动态链接库路径 #define LIB_CACULATE_PATH "/home/dahui/work/workspace/CStudy/src/libcalc.so" //函数指针 typedef int (*CAC_FUNC)(int, int); int main(void) { printf("!!!Hello World!!! "); /* prints !!!Hello World!!! */ void *handle; char *error; CAC_FUNC cac_func = NULL; //打开动态链接库 handle = dlopen(LIB_CACULATE_PATH, RTLD_LAZY); if (!handle) { fprintf(stderr, "%s ", dlerror()); exit(EXIT_FAILURE); } //清除之前存在的错误 dlerror(); //获取一个函数 *(void **) (&cac_func) = dlsym(handle, "add"); //cac_func = (CAC_FUNC) dlsym(handle, "add"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s ", error); exit(EXIT_FAILURE); } printf("add: %d ", (*cac_func)(2, 7)); cac_func = (CAC_FUNC) dlsym(handle, "sub"); printf("sub: %d ", cac_func(9, 2)); cac_func = (CAC_FUNC) dlsym(handle, "mul"); printf("mul: %d ", cac_func(3, 2)); cac_func = (CAC_FUNC) dlsym(handle, "div"); printf("div: %d ", cac_func(8, 2)); printf("!!!Hello World!!!"); /* prints !!!Hello World!!! */ //关闭动态链接库 dlclose(handle); //exit(EXIT_SUCCESS); printf("!!!Hello World!!!"); /* prints !!!Hello World!!! */ return EXIT_SUCCESS; }
输出: