2015-10-11 148 views
0

嗨,我想實現共享庫(動態鏈接)下面是我收到的錯誤爲下面的代碼,請幫我解決它 將共享庫作爲「無效轉換」從void *轉換爲double(*)(int *)時出錯?

error: invalid conversion from ‘void*’ to ‘double (*)(int*)’ [-fpermissive] 
    fn = dlsym(lib_handle, "ctest1"); 

ctest1.c

void ctest1(int *i) 
{ 
    *i=5; 
} 

以上ctest1.c是在以下hello.cc文件中使用的共享庫

#include <stdio.h> 
#include <stdlib.h> 
#include <dlfcn.h> 
#include "ctest1.h" // here i have declared the function of shared library 

int main(int argc, char **argv) 
{ 
    void *lib_handle; 
    void (*fn)(int *); 
    int x=990; 
    char *error; 

    lib_handle = dlopen("libp.so", RTLD_LAZY); // opening the shared library 
    if (!lib_handle) 
    { 
     fprintf(stderr, "%s\n", dlerror()); 
     exit(1); 
    } 

fn = dlsym(lib_handle, "ctest1"); //storing the address of shared library function 
    if ((error = dlerror()) != NULL) 
    { 
     fprintf(stderr, "%s\n", error); 
     exit(1); 
    } 

    fn(&x); 
    printf("getting x value from shared library=%d\n",x); 

    dlclose(lib_handle); 
    return 0; 
} 



+0

這看起來不像C++代碼。不要將C或C++標籤添加到無關的問題中。 – Olaf

回答

3

你只是調用了錯誤的編譯器。在中,您無法將其從void *轉換爲另一種指針類型而不投射。如果這不是您的代碼,那麼缺少演員表示代碼是而不是。請閱讀標籤wiki來了解,c和C++不是同一種語言,它們有點類似,但肯定不一樣。

這是從標準

6.3.2.3的草案n1570指針

  1. 作廢可轉化爲或者從一個指針到任何對象類型的指針。指向任何對象類型的指針可能會被轉換爲void指針並返回;結果應與原始指針相等。

如果這是你的代碼,你應該C和C區分++使用適當的文件擴展名,或強制編譯器使用相應的編譯器,我不推薦,剛修好的文件擴展名。

+0

能否請您詳細說明並幫我解決問題,謝謝 – user7953556

+0

您能否介紹一下如何編譯代碼? –

+0

首先我創建目標文件爲gcc -c ctest1.c然後創建一個目標文件,然後創建一個共享庫使用命令gcc -shared -o libp.so ctest1.o創建共享庫後,然後我編譯主代碼爲gcc -g -rdynamic -o progdl dynamic.cc -ldl – user7953556

1

dlsym返回一個void*並且您試圖將其存儲在函數指針中。在使用C++時,必須使用強制轉換才能成功(假設使用標記和文件結尾.cc,儘管代碼實際上是C)。

此外,您的類型聲稱該函數的返回類型爲double,但您的庫函數返回void。這將不得不被修復,否則你會遇到運行時問題。

+0

這不會改變你剛剛澄清的內容,是嗎? –

相關問題