如何从共享库函数获取返回值?
我读了一些关于加载共享库并调用其中的函数的教程。我在这两点上都取得了成功。只有一件事我在任何教程中都没有看到:
如何将共享库中的函数的值返回到主代码?
这是我的共享库源:
#include <stdio.h>
char* entry(){
printf("this is a working plugin\n");
return "here we go!";
}
当我调用它时,我在标准输出上得到“这是一个工作插件”。我现在的问题是,我如何才能将“Here we go”字符串返回到 main.c,它看起来像:
void *lib_handle;
void (*lib_func)();
...
lib_handle = dlopen("/home/tectu/projects/tibbers/plugins.so", RTLD_LAZY);
if(!lib_handle)
error("coudln't load plugins", NULL);
lib_func = dlsym(lib_handle, "entry");
if(!lib_func)
error("coudln't find symbol in plugin library", NULL);
(*lib_func)(); // here i call the entry() from the .so
这样的东西不起作用:
printf("return value: %s\n, (*lib_func)());
那么,有什么想法吗?
谢谢。
I read a few tutorials about loading shared libraries and call functions in them. I succeded on both points. There's just one thing I didn't see in any of the tutorials:
How do I return a value from a function in a shared library to the main code?
This is my shared library source:
#include <stdio.h>
char* entry(){
printf("this is a working plugin\n");
return "here we go!";
}
When i call it, i get "this is a working plugin" on the stdout. My question is now, how i can get the "here we go" string back to the main.c which looks like:
void *lib_handle;
void (*lib_func)();
...
lib_handle = dlopen("/home/tectu/projects/tibbers/plugins.so", RTLD_LAZY);
if(!lib_handle)
error("coudln't load plugins", NULL);
lib_func = dlsym(lib_handle, "entry");
if(!lib_func)
error("coudln't find symbol in plugin library", NULL);
(*lib_func)(); // here i call the entry() from the .so
Something like this does not work:
printf("return value: %s\n, (*lib_func)());
So, any ideas?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它在正确声明
lib_func
时起作用:您可能需要从
dlsym
中转换赋值。It works when
lib_func
is properly declared:You might need to cast in the assignment from
dlsym
.