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