Storing function pointer in std::function

前端 未结 3 748
囚心锁ツ
囚心锁ツ 2021-02-07 15:55

I\'m trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:

class DynamicLoader
{
  public:
    DynamicLoade         


        
3条回答
  •  渐次进展
    2021-02-07 16:43

    You just need to cast result of dlsym() call to a proper type. Here's a complete working example:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    class DynamicLoader
    {
    public:
        DynamicLoader(std::string const& filename) :
            m_handle(dlopen(filename.c_str(), RTLD_LAZY))
        {
            if (!m_handle)
            {
                throw std::logic_error("can't load library named \"" + filename + "\"");
            }
        }
    
        template
        std::function load(std::string const& functionName) const
        {
            dlerror();
            void* const result = dlsym(m_handle, functionName.c_str());
            if (!result)
            {
                char* const error = dlerror();
                if (error)
                {
                    throw std::logic_error("can't find symbol named \"" + functionName + "\": " + error);
                }
            }
    
            return reinterpret_cast(result);
        }
    
    private:
        void* const m_handle;
    };
    
    int main()
    {
        DynamicLoader const loader("/lib64/libz.so.1");
        auto const zlibVersion = loader.load("zlibVersion");
        std::cout << "zlib version: " << zlibVersion() << std::endl;
        return 0;
    }
    

提交回复
热议问题