2011-11-16 42 views
2

我閱讀了一些關於在其中加載共享庫和調用函數的教程。我在兩點都成功了。只有一件事我沒有在任何教程中看到:如何從共享庫函數獲取返回值?

如何從共享庫中的函數將值返回給主代碼?

這是我的共享庫來源:

#include <stdio.h> 

char* entry(){ 
    printf("this is a working plugin\n"); 

    return "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)()); 

因此,任何想法?

謝謝。

+0

也許是因爲這是一個靜態字符串?你有沒有嘗試返回一個int? – Bort

回答

4

它工作時lib_func正確聲明:

char* (*lib_func)(); 

您可能需要在分配投從dlsym

+0

太棒了!感謝您的幫助! – Tectu

相關問題