如何从共享库函数中获取返回值?

时间:2022-08-27 20:47:27

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:

当我打电话给它时,我在stdout上得到“这是一个有效的插件”。我现在的问题是,如何将“here we going”字符串返回到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

Something like this does not work:

这样的东西不起作用:

printf("return value: %s\n, (*lib_func)());

So, any ideas?

那么,有什么想法吗?

Thank you.

1 个解决方案

#1


4  

It works when lib_func is properly declared:

当正确声明lib_func时它可以工作:

char* (*lib_func)();

You might need to cast in the assignment from dlsym.

您可能需要从dlsym转换赋值。

#1


4  

It works when lib_func is properly declared:

当正确声明lib_func时它可以工作:

char* (*lib_func)();

You might need to cast in the assignment from dlsym.

您可能需要从dlsym转换赋值。