CEBL  2.1
SharedLoader.hpp
Go to the documentation of this file.
1 /*
2 * CEBL : CSU EEG Brain-Computer Interface Lab
3 *
4 * Author: Jeshua Bratman - jeshuabratman@gmail.com
5 *
6 * This file is part of CEBL.
7 *
8 * CEBL is free software; you can redistribute it and/or modify it.
9 * We only ask that if you use our code that you cite the source in
10 * your project or publication.
11 *
12 * EEG Group (www.cs.colostate.edu/eeg)
13 * Department of Computer Science
14 * Colorado State University
15 *
16 */
17 
27 #ifndef SHAREDLOADER_H
28 #define SHAREDLOADER_H
29 
30 
31 #include <dlfcn.h>
32 #include <iostream>
33 
34 using std::cerr;
35 using std::cout;
36 using std::endl;
37 
38 
39 template < typename T >
41 {
42 private:
43  bool loaded;
44  T* (*create_func)();
45  void (*destroy_func)(T *);
46  void *cls;//opened library
47 public:
48  SharedLoader();
49  ~SharedLoader();
50  void LoadLibrary(const char *);
51  T *New();
52  void Delete(T*);
53 
54  bool Loaded() { return loaded; }
55  void Close() { if(!loaded) { dlclose(cls);loaded = false; }}
56 
57 };
58 
59 //Constructor
60 template <typename T>
62 {
63  loaded = false;
64 }
65 
66 //Destructor
67 template <typename T>
69 {
70  if(loaded)
71  dlclose(cls);
72 }
73 
74 //create a new object
75 template <typename T>
77 {
78  //printf("Inside SharedLoader::New(): returning value from create function: function pointer = %x\n",create_func);
79  if(loaded)
80  return create_func();
81  else
82  return NULL;
83 }
84 
85 //delete an object
86 template <typename T>
88 {
89  if(obj != NULL)
90  destroy_func(obj);
91 }
92 
93 //load a shared library
94 template <typename T>
95 void SharedLoader<T>::LoadLibrary(const char *filename)
96 {
97  if(loaded)
98  {
99  dlclose(cls);
100  }
101  loaded = false;
102  //load the library
103  cls = dlopen(filename, RTLD_NOW);
104  if(!cls)
105  {
106  cerr << "Cannot load library: " << dlerror() << '\n';
107  loaded = false;
108  return;
109  }
110 
111  //reset errors
112  dlerror();
113 
114  //CREATE
115  typedef T* create_t();
116  create_func = (create_t*)dlsym(cls, "ObjectCreate");
117  const char* dlsym_error = dlerror();
118  if (dlsym_error)
119  {
120  cerr << "Cannot load ObjectCreate: " << dlsym_error << '\n';
121  loaded = false;
122  return;
123  }
124 
125  //DESTROY
126  typedef void destroy_t(T*);
127  destroy_func = (destroy_t*)dlsym(cls, "ObjectDestroy");
128  dlsym_error = dlerror();
129  if (dlsym_error)
130  {
131  cerr << "Cannot load ObjectDestroy: " << dlsym_error << '\n';
132  loaded = false;
133  return;
134  }
135  loaded = true;
136 
137 
138 }
139 #endif