本文介绍了在std :: function中存储函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在dlopen()/ dlsym()周围编写一个C ++ 0x包装函数来动态加载来自共享对象的函数:
code> 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)
{/ *抛出一些错误* /}
}
模板< class Signature>
std :: function< Signature> DynamicLoader :: load(std :: string const& functionName)
{
return< insert magic here> dlsym(itsHandle,functionName.c_str());
}
有一种方法可以将dlsym返回的void * std :: function?
解决方案
请尝试:
static_cast< Signature *>()
p>
完成测试:
#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;
}
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:
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());
}
Is there a way to convert the void* function pointer returned by dlsym into a std::function?
解决方案
try this:
static_cast<Signature*>()
seems works in VC10
complete test:
#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;
}
这篇关于在std :: function中存储函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!