RType
DLLoader.hpp
Go to the documentation of this file.
1 /*
2 ** EPITECH PROJECT, 2023
3 ** RType
4 ** File description:
5 ** DLLoader.cpp
6 */
7 
8 #pragma once
9 
10 #include "DLLoader.hpp"
11 #include "IGame.hpp"
12 #include "networking/server/ServerSocket.hpp"
13 #include <dlfcn.h>
14 #include <iostream>
15 
16 class DLLoader
17 {
18  public:
19  explicit DLLoader(const std::string &libraryPath)
20  {
21  std::cout << "Loading library: " << libraryPath << '\n';
22  handle = dlopen(libraryPath.c_str(), RTLD_LAZY);
23  if (!handle) {
24  std::cerr << "Cannot open library: " << dlerror() << '\n';
25  }
26  std::cout << "Library loaded\n";
27  }
28 
30  {
31  if (handle) {
32  dlclose(handle);
33  }
34  }
35 
36  IGame *getInstance(const std::string &functionName, const std::shared_ptr<ServerSocket> &socket)
37  {
38  dlerror();
39  auto *create = (create_t *)dlsym(handle, functionName.c_str());
40  const char *dlsym_error = dlerror();
41  if (dlsym_error) {
42  std::cerr << "Cannot load symbol '" << functionName << "': " << dlsym_error << '\n';
43  return nullptr;
44  }
45  if (!create) {
46  std::cerr << "Function '" << functionName << "' not found in the library.\n";
47  return nullptr;
48  }
49  std::cout << "Function '" << functionName << "' found in the library.\n";
50  return create(socket);
51  }
52 
53  private:
54  typedef IGame *create_t(std::shared_ptr<ServerSocket>);
55  void *handle = nullptr;
56 };