Skip to content

Commit c965926

Browse files
plugin manager example
1 parent 52b746e commit c965926

File tree

3 files changed

+60
-7
lines changed

3 files changed

+60
-7
lines changed

CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,4 @@ add_subdirectory(examples)
5050

5151
add_executable(main main.cpp)
5252
target_link_libraries(main ${COMON_LIBS})
53-
target_link_directories(main PUBLIC ${CMAKE_BINARY_DIR})
53+
target_link_directories(main PUBLIC ${CMAKE_BINARY_DIR})

examples/PluginManager.h

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#ifndef TINY_PLUGIN_PLUGIN_MANAGER_H
2+
#define TINY_PLUGIN_PLUGIN_MANAGER_H
3+
4+
#pragma once
5+
6+
#include <tiny_plugin/SharedLibrary.h>
7+
#include <unordered_map>
8+
#include <mutex>
9+
10+
class PluginManager
11+
{
12+
private:
13+
std::unordered_map<std::string, std::shared_ptr<SharedLibrary>> plugins;
14+
std::mutex mtx;
15+
16+
public:
17+
PluginManager()
18+
{
19+
}
20+
21+
void load_library(const std::string &name, const std::string &path = "")
22+
{
23+
std::lock_guard<std::mutex> lock(mtx);
24+
plugins[name] = std::make_shared<SharedLibrary>(name, path);
25+
}
26+
27+
template <typename T, typename... Args>
28+
std::shared_ptr<T> create_instance_sptr(const std::string &name, Args... args)
29+
{
30+
std::lock_guard<std::mutex> lock(mtx);
31+
if (plugins.find(name) == plugins.end())
32+
{
33+
std::cerr << "Plugin not found, load library before making instance!" <<std::endl;
34+
return nullptr;
35+
}
36+
else
37+
{
38+
return plugins[name]->create_instance_sptr<T>(args...);
39+
}
40+
}
41+
42+
~PluginManager()
43+
{
44+
}
45+
};
46+
47+
#endif // TINY_PLUGIN_PLUGIN_MANAGER_H

main.cpp

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11

22
#include <memory>
33

4-
#include <tiny_plugin/SharedLibrary.h>
4+
#include "examples/PluginManager.h"
55

66
int main()
77
{
8-
SharedLibrary simple("SimplePlugin");
8+
PluginManager manager;
99

10-
if (simple.is_loaded())
11-
{
12-
auto instance = simple.create_instance_sptr<void *>();
13-
}
10+
manager.load_library("SimplePlugin");
11+
manager.load_library("ComplexPlugin");
12+
13+
// simple shared library instance
14+
auto instance_simple = manager.create_instance_sptr<void *>("SimplePlugin");
15+
16+
// shared library instance with arguments, make sure to pass valid arguments
17+
auto x = std::make_shared<int>(123);
18+
auto instance_complex = manager.create_instance_sptr<void *>("ComplexPlugin", x);
19+
auto instance_simple2 = manager.create_instance_sptr<void *>("SimplePlugin2");
1420

1521
return 0;
1622
}

0 commit comments

Comments
 (0)