求助,c语言调用so文件
要求用c语言写一个调用so文件的程序: 该程序中有一个循环(循环600次),每次循环启动一个线程,该线程去调用so文件。
请帖个例子程序,多谢了!
[解决办法]
用dlopen函数打开你要使用的so动态库
用dlsym函数获取该动态库中你指定的函数的函数指针
使用这个函数指针即可实现函数的调用
用dlclose函数关闭动态库
编译源代码时,如果是gcc编译器,加上编译选项: -ldl
意思是编译时链接dl库,因为上面3个函数是dl库里的。
[解决办法]
下述代码动态加载了系统的 libc.so.6 库,获取 printf 的入口地址,并使用函数指针调用之,如下
- C/C++ code
#include <dlfcn.h>typedef int (* pf_printf)(const char *format, ...);int main(void){ void* handle = dlopen("libc.so.6", RTLD_LAZY); if (! handle) return -1; dlerror(); pf_printf mypf = (pf_printf)dlsym(handle, "printf"); if(0 != dlerror()) return -2; mypf("this is a test\n"); dlclose(handle); return 0;}
[解决办法]
编译选项如下:
gcc -g -Wall -o dl dl.c -ldl
[解决办法]
LZ留邮箱,晚上发给你