-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPluginInterface.cpp
More file actions
66 lines (52 loc) · 1.93 KB
/
PluginInterface.cpp
File metadata and controls
66 lines (52 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "PluginInterface.h"
#include <windows.h>
#include <string>
#include <stdexcept>
#include <iostream>
#include <mutex>
// User-side implementation of PluginInterface
class LibraryLoader
{
const HINSTANCE m_DllHandle;
const std::string m_sFilename;
public:
LibraryLoader(const std::filesystem::path& DllPath)
: m_DllHandle(LoadLibrary(DllPath.c_str()))
, m_sFilename(DllPath.filename().string())
{
if (!m_DllHandle)
throw std::runtime_error(std::string("Failed to load dll: ") + m_sFilename);
std::cout << "Successfully loaded " << m_sFilename << ".\n";
}
~LibraryLoader()
{
std::cout << "Unloading " << m_sFilename << ".\n";
FreeLibrary(m_DllHandle);
}
template <class T>
T GetFunctionFromDll(const char* sName)
{
T Func = (T)GetProcAddress(m_DllHandle, sName);
if (Func == nullptr)
throw std::runtime_error(std::string("Could not find function \"") + sName + "\" in Dll: " + m_sFilename);
return Func;
}
};
PluginInterfacePtr createPluginInterface(const std::filesystem::path& DllPath)
{
std::shared_ptr<LibraryLoader> pLibrary = std::make_shared<LibraryLoader>(DllPath);
typedef PluginInterface* (__cdecl* createPluginInterfaceProc)(void);
createPluginInterfaceProc FuncCreate =
pLibrary->GetFunctionFromDll<createPluginInterfaceProc>("createPluginInterface");
typedef void(__cdecl* releasePluginInterfaceProc)(PluginInterface*);
releasePluginInterfaceProc FuncRelease =
pLibrary->GetFunctionFromDll<releasePluginInterfaceProc>("releasePluginInterface");
PluginInterfacePtr pPluginInterface(FuncCreate(),
[pLibrary, FuncRelease](PluginInterface* pPluginInterface) // We bind pLibrary to the lambda to ensure it is not destroyed before the PluginInterface
{
std::cout << "Releasing PluginInterface: " << pPluginInterface->getName() << ".\n";
FuncRelease(pPluginInterface);
});
std::cout << "Created PluginInterface: " << pPluginInterface->getName() << ".\n";
return pPluginInterface;
}