update on dbus
[profile/ivi/audiomanager.git] / AudioManagerDaemon / pluginTemplate.h
1 /*
2  * pluginTemplate.h
3  *
4  *  Created on: Jul 27, 2011
5  *      Author: christian
6  */
7
8 #ifndef PLUGINTEMPLATE_H_
9 #define PLUGINTEMPLATE_H_
10
11 #include <iostream>
12 #include <stdio.h>
13 #include <dirent.h>
14 #include <dlfcn.h>
15 #include <libgen.h>
16 #include <unistd.h>
17 #include <string>
18
19 #include "audioManagerIncludes.h"
20
21 template<class T>T* getCreateFunction(std::string libname) {
22
23         // cut off directories
24         char* fileWithPath = const_cast<char*>(libname.c_str());
25         std::string libFileName = basename(fileWithPath);
26
27         // cut off "lib" in front and cut off .so end"
28         std::string createFunctionName = libFileName.substr(3, libFileName.length() - 6) + "Factory";
29         DLT_LOG(AudioManager,DLT_LOG_INFO, DLT_STRING("Lib entry point name "),DLT_STRING(createFunctionName.c_str()));
30
31         // open library
32         void *libraryHandle;
33         dlerror(); // Clear any existing error
34         libraryHandle = dlopen(libname.c_str(), RTLD_NOW /*LAZY*/);
35         const char* dlopen_error = dlerror();
36         if (!libraryHandle || dlopen_error)
37         {
38                 DLT_LOG(AudioManager,DLT_LOG_INFO, DLT_STRING("dlopen failed"),DLT_STRING(dlopen_error));
39                 return 0;
40         }
41
42         // get entry point from shared lib
43         dlerror(); // Clear any existing error
44         DLT_LOG(AudioManager,DLT_LOG_INFO, DLT_STRING("loading external function with name"),DLT_STRING(createFunctionName.c_str()));
45
46         union
47         {
48                 void* voidPointer;
49                 T* typedPointer;
50         } functionPointer;
51
52         // Note: direct cast is not allowed by ISO C++. e.g.
53         // T* createFunction = reinterpret_cast<T*>(dlsym(libraryHandle, createFunctionName.c_str()));
54         // compiler warning: "forbids casting between pointer-to-function and pointer-to-object"
55
56         functionPointer.voidPointer = dlsym(libraryHandle, createFunctionName.c_str());
57         T* createFunction = functionPointer.typedPointer;
58
59         const char* dlsym_error = dlerror();
60         if (!createFunction || dlsym_error)
61         {
62                 DLT_LOG(AudioManager,DLT_LOG_INFO, DLT_STRING("Failed to load shared lib entry point"),DLT_STRING(dlsym_error));
63         }
64
65         return createFunction;
66 }
67
68
69 #endif /* PLUGINTEMPLATE_H_ */