1
0

chaiscript_posix.hpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // This file is distributed under the BSD License.
  2. // See "license.txt" for details.
  3. // Copyright 2009-2012, Jonathan Turner ([email protected])
  4. // Copyright 2009-2017, Jason Turner ([email protected])
  5. // http://www.chaiscript.com
  6. #ifndef CHAISCRIPT_POSIX_HPP_
  7. #define CHAISCRIPT_POSIX_HPP_
  8. namespace chaiscript
  9. {
  10. namespace detail
  11. {
  12. struct Loadable_Module
  13. {
  14. struct DLModule
  15. {
  16. explicit DLModule(const std::string &t_filename)
  17. : m_data(dlopen(t_filename.c_str(), RTLD_NOW))
  18. {
  19. if (m_data == nullptr)
  20. {
  21. throw chaiscript::exception::load_module_error(dlerror());
  22. }
  23. }
  24. DLModule(DLModule &&) = default;
  25. DLModule &operator=(DLModule &&) = default;
  26. DLModule(const DLModule &) = delete;
  27. DLModule &operator=(const DLModule &) = delete;
  28. ~DLModule()
  29. {
  30. dlclose(m_data);
  31. }
  32. void *m_data;
  33. };
  34. template<typename T>
  35. struct DLSym
  36. {
  37. DLSym(DLModule &t_mod, const std::string &t_symbol)
  38. : m_symbol(cast_symbol(dlsym(t_mod.m_data, t_symbol.c_str())))
  39. {
  40. if (!m_symbol)
  41. {
  42. throw chaiscript::exception::load_module_error(dlerror());
  43. }
  44. }
  45. static T cast_symbol(void *p)
  46. {
  47. union cast_union
  48. {
  49. T func_ptr;
  50. void *in_ptr;
  51. };
  52. cast_union c;
  53. c.in_ptr = p;
  54. return c.func_ptr;
  55. }
  56. T m_symbol;
  57. };
  58. Loadable_Module(const std::string &t_module_name, const std::string &t_filename)
  59. : m_dlmodule(t_filename), m_func(m_dlmodule, "create_chaiscript_module_" + t_module_name),
  60. m_moduleptr(m_func.m_symbol())
  61. {
  62. }
  63. DLModule m_dlmodule;
  64. DLSym<Create_Module_Func> m_func;
  65. ModulePtr m_moduleptr;
  66. };
  67. }
  68. }
  69. #endif