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 {
22
23 template <class RETURN_TYPE, class... IN_TYPES> class DynamicFCN;
24
25 template <class RETURN_TYPE, class... IN_TYPES> class DynamicFCN<RETURN_TYPE(IN_TYPES...)> {
26 private:
27 struct LibHandle {
28 void *handle = {nullptr};
29 LibHandle(void *handle) : handle(handle) {};
30 ~LibHandle() {
31 if(handle != nullptr) dlclose(handle);
32 }
33 operator void *() { return handle; }
34 };
35
36 std::shared_ptr<LibHandle> m_handle = {nullptr};
37 RETURN_TYPE (*m_fcn)(IN_TYPES...) = {nullptr};
38
39 public:
40 DynamicFCN() = default;
41 DynamicFCN(const std::string &lib, const std::string &name) : m_handle(std::make_shared<LibHandle>(dlopen(lib.c_str(), RTLD_NOW))) { set(*m_handle, name); }
42 DynamicFCN(void *handle, const std::string &name) : m_handle(std::make_shared<LibHandle>(handle)) { set(handle, name); }
44
45 bool set(const std::string &lib, const std::string &name) {
46 DEBUG("Linking handle: " << lib << ":" << name);
47 m_handle = std::make_shared<LibHandle>(dlopen(lib.c_str(), RTLD_NOW));
48 if(!m_handle) {
49 DEBUG(dlerror());
50 return false;
51 }
52 return set(*m_handle, name);
53 }
54 bool set(void *handle, const std::string &name, bool isFatal = false) {
55 m_fcn = (RETURN_TYPE (*)(IN_TYPES...))dlsym(handle, name.c_str());
56 if(m_fcn == nullptr) {
57 if(!isFatal)
58 ERROR("Failed to link: " << name << " error: " << dlerror());
59 else
60 FATAL("Failed to link: " << name << " error: " << dlerror());
61 return false;
62 }
63 return true;
64 }
65 RETURN_TYPE operator()(IN_TYPES... input) const { return (*m_fcn)(input...); }
66 bool isLinked() const { return m_fcn != nullptr; }
67 };
68} // namespace AmpGen
69
70#endif
bool set(const std::string &lib, const std::string &name)
Definition DynamicFCN.h:45
bool set(void *handle, const std::string &name, bool isFatal=false)
Definition DynamicFCN.h:54
RETURN_TYPE operator()(IN_TYPES... input) const
Definition DynamicFCN.h:65
DynamicFCN(void *handle, const std::string &name)
Definition DynamicFCN.h:42
DynamicFCN(const std::string &lib, const std::string &name)
Definition DynamicFCN.h:41
#define ERROR(X)
Used for printing errors messages, and will always be printed.
Definition MsgService.h:85
#define DEBUG(X)
Used for printing verbose debugging messages, only if DEBUGLEVEL is defined.
Definition MsgService.h:69
#define FATAL(X)
Used for printing fatal errors messages, and will always be printed and will terminate the process af...
Definition MsgService.h:92
Wrapper to give templated interface to a function contained in a dynamically linked library.
Definition DynamicFCN.h:23