我试图在dlopen()/ dlsym()周围编写一个C 0x包装来动态地从共享对象加载函数:
class DynamicLoader { public: DynamicLoader(std::string const& filename); template<class Signature> std::function<Signature> load(std::string const& functionName); private: void *itsLibraryHandle; }; DynamicLoader::DynamicLoader(std::string const& filename) { itsLibraryHandle = dlopen(filename.c_str(),RTLD_LAZY); if(!itsLibraryHandle) { /* Throw Some Error */ } } template<class Signature> std::function<Signature> DynamicLoader::load(std::string const& functionName) { return <insert magic here> dlsym(itsHandle,functionName.c_str()); }
解决方法
尝试这个:
static_cast<Signature*>()
似乎在VC10中有效
完成测试:
#include <functional> void test() {} template <typename Signature> std::function<Signature> cast(void* f) { return static_cast<Signature*>(f); } int main() { std::function<void()> f = cast<void()>(&test); return 0; }