C/C++函数动态加载器(helper)

C/C++ function dynamic loader (helper)

本文关键字:helper 加载 动态 C++ 函数      更新时间:2023-10-16

我试图实现一个助手类,以便轻松加载.dll或.so文件并获取函数指针。以下代码在ubuntu 16和VS‘2015上编译并运行良好,但我面临着在Centos 7(旧GCC 4.8.5(上编译它的问题…

它抱怨

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使用和constexpr报告了的问题

欢迎任何想法

完整代码:

#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;
};