代码拉取完成,页面将自动刷新
/*当需要连接动态库时,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);
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。