Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing function pointer in std::function

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?

like image 207
rcv Avatar asked Jan 22 '11 22:01

rcv


2 Answers

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;
}
like image 181
Andriy Tylychko Avatar answered Sep 28 '22 09:09

Andriy Tylychko


Based on what I see here: http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html

#include <boost/function_types/components.hpp>
#include <boost/function_types/function_pointer.hpp>

template< typename Signature >
std::function<Signature> DynamicLoader::load(std::string const& name)
{
  namespace ft = boost::function_types;
  typedef typename ft::function_pointer< typename ft::components<Signature>::type >::type fp_t;
  fp_t fun_ptr;

  *reinterpret_cast<void**>(&fun_ptr) = dlsym(itsHandle, name.c_str());

  return fun_ptr;
}

I've never used dlsym so I don't understand why the cast is being done that way and not simply casting dlsym's return like so:

fun_ptr = reinterpret_cast<fp_t>(dlsym(itsHandle, name.c_str());
like image 26
Edward Strange Avatar answered Sep 28 '22 09:09

Edward Strange