1

我有一個類可以動態加載.dll.so或同等產品。從那裏,它將返回指向你試圖找到的任何函數的指針。不幸的是,我在實現中遇到了兩個問題。使用可變參數模板「沒有與呼叫匹配的功能」

  1. 如果我用的是「啞巴」函數返回void *的函數指針,我得到warning: ISO C++ forbids casting between pointer-to-function and pointer-to-object,當我嘗試將它們操縱爲形式,我可以使用。
  2. 如果我嘗試使用帶有可變參數模板和類型安全的'智能'函數,我無法獲得它的編譯。 error: no matching function for call to ‘Library::findFunction(std::string&)’是在這裏等待我的唯一的東西。正如你從下面的代碼可以看到的,這應該匹配函數簽名。一旦編譯完成,問題1也將出現在這裏。

作爲參考,我正在編譯Ubuntu 10.10 x86_64g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5。我也嘗試編譯g++-4.5 (Ubuntu/Linaro 4.5.1-7ubuntu2) 4.5.1然而這並沒有改變任何東西。

#include <string> 
#include <stdio.h> 

class Library 
{ 
public: 
    Library(const std::string& path) {} 
    ~Library() {} 

    void* findFunction(const std::string& funcName) const 
    { 
     // dlsym will return a void* as pointer-to-function here. 
     return 0; 
    } 

    template<typename RetType, typename... T> 
    RetType (*findFunction(const std::string& funcName))(T... Ts) const 
    { 
     return (RetType (*)(...))findFunction(funcName); 
    } 

}; 

int main() 
{ 
    Library test("/usr/lib/libsqlite3.so"); 

    std::string name = "sqlite3_libversion"; 
    const char* (*whatwhat)() = test.findFunction<const char*, void>(name); 
    // this SHOULD work. it's the right type now! >=[ 

    //const char* ver3 = whatwhat(); 
    //printf("blah says \"%s\"\n", ver3); 
} 

回答

1

我認爲你需要返回的函數簽名改爲T...,而不是僅僅...否則它需要一個變量的arglist即使它應該只是空的。

template<typename RetType, typename... T> 
RetType (*findFunction(const std::string& funcName))(T... Ts) const 
{ 
    return (RetType (*)(T...))findFunction(funcName); 
} 

然後在類型列表中調用它沒有void,它應該工作:

const char* (*whatwhat)() = test.findFunction<const char*>(name); 

有了這些改變它編譯爲我的gcc-4.5.1http://ideone.com/UFbut

+0

哇,謝謝!這解決了我列表中的第二個問題。你知道我如何解決在指針到對象和指向函數之間轉換的警告嗎? – Sticky 2012-01-18 01:45:48

+0

有趣的是,一些網絡搜索顯示第一個問題可能無法解決:http://www.trilithium.com/johan/2004/12/problem-with-dlsym/ - 這是一箇舊鏈接,但我不要以爲這種行爲已經改變了。 – tzaman 2012-01-18 01:53:25

+0

是的,我只是自己找到那篇文章。我不認爲我能做些什麼,只是GCC會生成工作代碼,但仍然抱怨。那篇文章在Windows上也提到了一個類似但相反的問題,所以我認爲無論我做什麼,這都會成爲一個問題。鑑於此,非常感謝你幫助我解決這個問題,現在已經讓我煩惱了:) – Sticky 2012-01-18 01:59:07