1 Star 1 Fork 0

qcliu / testC

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
testldopen.c 1.47 KB
一键复制 编辑 原始数据 按行查看 历史
qcliu 提交于 2015-03-31 21:06 . dlopen
/*当需要连接动态库时,gcc编译时需要在最后加入-ldl*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*使用dlopen需要导入头文件*/
#include <dlfcn.h>
typedef void(*pfunc)();
void throwException(char* e)
{
printf("Exception:%s\n", e);
exit(0);
}
void main(int argc, char** argv)
{
int i;
char* env;
char* libname = "libtestso.so";
i = 10;
env = getenv("LD_LIBRARY_PATH");
if (env == NULL)
throwException("not set LD_LIBRARY_PATH");
for(i=1; i<strlen(env); i++)
{
if (env[i] == ':')
break;
}
int len = strlen(libname);
char path[i+len+2];
memcpy(path, &env[1], i-1);
strcat(strcat(path, "/"), libname);
printf("%s\n", path);
/*dlopen()第一个参数是库的路径,第二个参数是打开方式。
*返回值是一个指针。给dlsym()使用。
*/
void* handle = dlopen(path, RTLD_LAZY);
if (handle == NULL)
throwException("handle is NULL");
/*dlsym(库的指针,库里面的函数名)
*返回一个函数指针。
*/
void* func = dlsym(handle, "printInt");
if (func == NULL)
throwException("func is NULL");
/*指针使用时需要根据函数的返回值和参数进行强制类型转换。
*转换规则:(返回类型(*)(参数类型...))
* ((void(*)(int))func)也是正确的,对参数没有限制。
*((void)(*)(int)func)是错误的。返回类型不需要括号。
**/
((void(*)())func)(i);
}
C
1
https://gitee.com/qcliu/testC.git
git@gitee.com:qcliu/testC.git
qcliu
testC
testC
master

搜索帮助