1#ifndef AMPGEN_DYNAMICFCN_H
2#define AMPGEN_DYNAMICFCN_H
24 template <
class RETURN_TYPE,
class ...IN_TYPES>
27 template <
class RETURN_TYPE,
class ...IN_TYPES>
32 void* handle={
nullptr};
33 LibHandle(
void* handle) : handle(handle) {};
34 ~LibHandle(){
if( handle !=
nullptr) dlclose(handle); }
35 operator void*(){
return handle; }
38 std::shared_ptr<LibHandle> m_handle = {
nullptr};
39 RETURN_TYPE ( *m_fcn )( IN_TYPES... ) = {
nullptr};
43 DynamicFCN(
const std::string& lib,
const std::string& name ) :
44 m_handle(std::make_shared<LibHandle>(dlopen( lib.c_str(), RTLD_NOW ))) {
47 DynamicFCN(
void* handle,
const std::string& name ) : m_handle(std::make_shared<LibHandle>(handle)) {
set( handle, name ); }
50 bool set(
const std::string& lib,
const std::string& name )
52 DEBUG(
"Linking handle: " << lib <<
":" << name );
53 m_handle = std::make_shared<LibHandle>( dlopen( lib.c_str(), RTLD_NOW ) );
58 return set(*m_handle,name);
60 bool set(
void* handle,
const std::string& name,
bool isFatal =
false)
62 m_fcn = (RETURN_TYPE( * )( IN_TYPES... ))dlsym( handle, name.c_str() );
63 if ( m_fcn ==
nullptr ) {
64 if( !isFatal )
ERROR(
"Failed to link: " << name <<
" error: " << dlerror() );
65 else FATAL(
"Failed to link: " << name <<
" error: " << dlerror() );
70 RETURN_TYPE
operator()( IN_TYPES... input )
const {
return ( *m_fcn )( input... ); }
71 bool isLinked()
const {
return m_fcn !=
nullptr; }
bool set(const std::string &lib, const std::string &name)
bool set(void *handle, const std::string &name, bool isFatal=false)
RETURN_TYPE operator()(IN_TYPES... input) const
DynamicFCN(void *handle, const std::string &name)
DynamicFCN(const std::string &lib, const std::string &name)
#define ERROR(X)
Used for printing errors messages, and will always be printed.
#define DEBUG(X)
Used for printing verbose debugging messages, only if DEBUGLEVEL is defined.
#define FATAL(X)
Used for printing fatal errors messages, and will always be printed and will terminate the process af...
Wrapper to give templated interface to a function contained in a dynamically linked library.