1
我有一个类可以动态加载.dll
或.so
或同等产品。从那里,它将返回指向你试图找到的任何函数的指针。不幸的是,我在实现中遇到了两个问题。使用可变参数模板“没有与呼叫匹配的功能”
- 如果我用的是“哑巴”函数返回void *的函数指针,我得到
warning: ISO C++ forbids casting between pointer-to-function and pointer-to-object
,当我尝试将它们操纵为形式,我可以使用。 - 如果我尝试使用带有可变参数模板和类型安全的'智能'函数,我无法获得它的编译。
error: no matching function for call to ‘Library::findFunction(std::string&)’
是在这里等待我的唯一的东西。正如你从下面的代码可以看到的,这应该匹配函数签名。一旦编译完成,问题1也将出现在这里。
作为参考,我正在编译Ubuntu 10.10 x86_64
与g++ (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);
}
哇,谢谢!这解决了我列表中的第二个问题。你知道我如何解决在指针到对象和指向函数之间转换的警告吗? – Sticky 2012-01-18 01:45:48
有趣的是,一些网络搜索显示第一个问题可能无法解决:http://www.trilithium.com/johan/2004/12/problem-with-dlsym/ - 这是一个旧链接,但我不要以为这种行为已经改变了。 – tzaman 2012-01-18 01:53:25
是的,我只是自己找到那篇文章。我不认为我能做些什么,只是GCC会生成工作代码,但仍然抱怨。那篇文章在Windows上也提到了一个类似但相反的问题,所以我认为无论我做什么,这都会成为一个问题。鉴于此,非常感谢你帮助我解决这个问题,现在已经让我烦恼了:) – Sticky 2012-01-18 01:59:07