【发布时间】:2012-01-18 01:26:36
【问题描述】:
我有一个旨在动态加载.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);
}
【问题讨论】:
标签: c++ c++11 function-pointers variadic-templates dynamic-loading