实现了动态加载标准库中的数学函数库,输入函数名及参数,返回计算结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | /* * #include <dlfcn.h> * void *dlopen( const char *file, int mode ); * void *dlsym( void *restrict handle, const char *restrict name ); * char *dlerror(); * char *dlclose( void *handle ); * dlopen 使对象文件可被程序访问 * dlsym 获取执行了 dlopen 函数的对象文件中的符号的地址 * dlerror 返回上一次出现错误的字符串错误 * dlclose 关闭目标文件 */ #include <stdio.h> #include <string.h> #include <dlfcn.h> int main() { typedef double(*F)(double); void* handle; F func = NULL; char list[256]; char method[16]; double arg; if(!(handle = dlopen("libm.so", RTLD_LAZY))) { //~ 加载并关联标准数学函数库 printf("%s\n", dlerror()); return 1; } while(1) { printf("Input like 'sqrt 3' or 'bye' to quit \n>"); fgets(list, sizeof(list), stdin); //~ 接受输入 if(!strncmp(list, "bye", 3)) break; sscanf(list, "%s\n%lf", method, &arg); //~ 解析参数 if(!(func =(F) dlsym(handle, method))) { //~ 查找函数地址 printf("%s\n", dlerror()); continue; } printf("%f\n", (*func)(arg)); } dlclose(handle); //~ 解除关联 return 0; } |
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Be the first to comment on this entry.