簡體   English   中英

C/C++ function 動態加載器(助手)

[英]C/C++ function dynamic loader (helper)

我嘗試實現一個助手 class 以輕松加載.dll 或.so 文件並獲取 function 指針。 以下代碼在 ubuntu 16 和 VS'2015 上編譯並運行良好,但在 Centos 7(舊 Z32D8B233E3C28A267D....DZ5488)上編譯時遇到了問題。

它抱怨

template< class T> constexpr bool ext_is_function_v = is_function<T>::value;

錯誤消息(見下文)沒有給出失敗原因的任何線索!

錯誤:constexpr bool ext_is_function_v = is_function::value 的模板聲明;

是 constexpr 嗎? 還是模板別名? 我查看了 GCC4.8 支持的 C++11 功能,一切似乎都很好。 但是 CodeExplorer 報告了usingconstexpr的問題

歡迎任何想法

完整代碼:

#include <type_traits>
namespace std { /* std lib extension with 2 helpers C++14 or C++17*/
    template< bool B, class T = void >
    using ext_enable_if_t = typename enable_if<B, T>::type;
    template< class T> constexpr bool ext_is_function_v = is_function<T>::value;
}
#if defined(_WIN64) || defined(_WIN32)
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#else
#include <dlfcn.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#endif
template<typename F_PTR_T>
class ProcPtr {
public:
    explicit ProcPtr(F_PTR_T ptr) : _ptr(ptr) {}
    template <typename T, typename = std::ext_enable_if_t<std::ext_is_function_v<T>>>
    operator T *() const { return reinterpret_cast<T *>(_ptr); }
private:
    F_PTR_T _ptr;
};
template<typename MODULE_T, typename F_PTR_T>
class DllHelper {
public:
    explicit DllHelper(const char* filename) :
#if defined(_WIN64) || defined(_WIN32)
        _module(LoadLibrary(filename)) 
#else
        _module(dlopen(filename, RTLD_LAZY)) 
#endif
    {
        if(_module == NULL) {
            throw std::runtime_error((boost::format("Error while loading %1%") % filename).str().c_str());
        }
    }

    ~DllHelper() {
#if defined(_WIN64) || defined(_WIN32)
        FreeLibrary(_module);
#else
        dlclose(_module);
#endif
    }

    ProcPtr<F_PTR_T> operator[](const char* proc_name) const {
#if defined(_WIN64) || defined(_WIN32)
        return ProcPtr<F_PTR_T>(GetProcAddress(_module, proc_name));
#else
        return ProcPtr<F_PTR_T>(dlsym(_module, proc_name));
#endif
    }

private:
    MODULE_T _module;
};

最后,我只返回 C++11 而不嘗試擴展 std 命名空間。

#if defined(_WIN64) || defined(_WIN32)
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#else
#include <dlfcn.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#endif
template<typename F_PTR_T>
class ProcPtr {
public:
    explicit ProcPtr(F_PTR_T ptr) : _ptr(ptr) {}
    template <typename T, typename = typename std::enable_if< std::is_function<T>::value >::type >
    operator T *() const { return reinterpret_cast<T *>(_ptr); }
private:
    F_PTR_T _ptr;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM