AmpGen 2.1
Loading...
Searching...
No Matches
DynamicFCN.h
Go to the documentation of this file.
1#ifndef AMPGEN_DYNAMICFCN_H
2#define AMPGEN_DYNAMICFCN_H
3
4#include "AmpGen/MsgService.h"
5#include <dlfcn.h>
6#include <iostream>
7
8namespace AmpGen
9{
23
24 template <class RETURN_TYPE, class ...IN_TYPES>
25 class DynamicFCN;
26
27 template <class RETURN_TYPE, class ...IN_TYPES>
28 class DynamicFCN<RETURN_TYPE( IN_TYPES... )>
29 {
30 private:
31 struct LibHandle {
32 void* handle={nullptr};
33 LibHandle(void* handle) : handle(handle) {};
34 ~LibHandle(){ if( handle !=nullptr) dlclose(handle); }
35 operator void*(){ return handle; }
36 };
37
38 std::shared_ptr<LibHandle> m_handle = {nullptr};
39 RETURN_TYPE ( *m_fcn )( IN_TYPES... ) = {nullptr};
40
41 public:
42 DynamicFCN() = default;
43 DynamicFCN( const std::string& lib, const std::string& name ) :
44 m_handle(std::make_shared<LibHandle>(dlopen( lib.c_str(), RTLD_NOW ))) {
45 set(*m_handle,name);
46 }
47 DynamicFCN( void* handle, const std::string& name ) : m_handle(std::make_shared<LibHandle>(handle)) { set( handle, name ); }
49
50 bool set( const std::string& lib, const std::string& name )
51 {
52 DEBUG("Linking handle: " << lib << ":" << name );
53 m_handle = std::make_shared<LibHandle>( dlopen( lib.c_str(), RTLD_NOW ) );
54 if( !m_handle ){
55 DEBUG( dlerror() );
56 return false;
57 }
58 return set(*m_handle,name);
59 }
60 bool set( void* handle, const std::string& name, bool isFatal = false)
61 {
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() );
66 return false;
67 }
68 return true;
69 }
70 RETURN_TYPE operator()( IN_TYPES... input ) const { return ( *m_fcn )( input... ); }
71 bool isLinked() const { return m_fcn != nullptr; }
72 };
73} // namespace AmpGen
74
75#endif
bool set(const std::string &lib, const std::string &name)
Definition DynamicFCN.h:50
bool set(void *handle, const std::string &name, bool isFatal=false)
Definition DynamicFCN.h:60
RETURN_TYPE operator()(IN_TYPES... input) const
Definition DynamicFCN.h:70
DynamicFCN(void *handle, const std::string &name)
Definition DynamicFCN.h:47
DynamicFCN(const std::string &lib, const std::string &name)
Definition DynamicFCN.h:43
#define ERROR(X)
Used for printing errors messages, and will always be printed.
Definition MsgService.h:80
#define DEBUG(X)
Used for printing verbose debugging messages, only if DEBUGLEVEL is defined.
Definition MsgService.h:66
#define FATAL(X)
Used for printing fatal errors messages, and will always be printed and will terminate the process af...
Definition MsgService.h:87
Wrapper to give templated interface to a function contained in a dynamically linked library.
Definition DynamicFCN.h:25