MXVM 1.8.1
Virtual Machine, Compiler, and Pascal Frontend
Loading...
Searching...
No Matches
function.hpp
Go to the documentation of this file.
1
6#ifndef __FUNCTION_H__
7#define __FUNCTION_H__
8
9#include <dlfcn.h>
10#include <stdexcept>
11
12namespace mxvm {
13
14 template <typename Sig>
15 class Function;
24 template <typename R, typename... Args>
25 class Function<R(Args...)> {
26 public:
27 using Fn = R (*)(Args...);
28
35 Function(char const *lib, char const *name) {
36 handle = dlopen(lib, RTLD_LAZY);
37 if (!handle)
38 throw std::runtime_error(dlerror());
39 void *sym = dlsym(handle, name);
40 if (!sym) {
41 dlclose(handle);
42 throw std::runtime_error(dlerror());
43 }
44 fn = reinterpret_cast<Fn>(sym);
45 }
46
52 Function(char const *name) {
53 handle = dlopen(nullptr, RTLD_LAZY);
54 if (!handle)
55 throw std::runtime_error(dlerror());
56 void *sym = dlsym(handle, name);
57 if (!sym) {
58 dlclose(handle);
59 throw std::runtime_error(dlerror());
60 }
61 fn = reinterpret_cast<Fn>(sym);
62 }
63
65 if (handle)
66 dlclose(handle);
67 }
68
69 Function(const Function &) = delete;
70 Function &operator=(const Function &) = delete;
71
72 Function(Function &&other) noexcept : handle(other.handle), fn(other.fn) {
73 other.handle = nullptr;
74 other.fn = nullptr;
75 }
76 Function &operator=(Function &&other) noexcept {
77 if (this != &other) {
78 if (handle)
79 dlclose(handle);
80 handle = other.handle;
81 fn = other.fn;
82 other.handle = nullptr;
83 other.fn = nullptr;
84 }
85 return *this;
86 }
87
89 R operator()(Args... args) const {
90 if (!fn)
91 throw std::runtime_error("Null function pointer");
92 return fn(std::forward<Args>(args)...);
93 }
94
95 private:
96 void *handle = nullptr;
97 Fn fn = nullptr;
98 };
99
100} // namespace mxvm
101
102#endif
Function(char const *name)
Load a function from the main program's symbol table.
Definition function.hpp:52
Function(Function &&other) noexcept
Definition function.hpp:72
Function & operator=(Function &&other) noexcept
Definition function.hpp:76
Function & operator=(const Function &)=delete
Function(const Function &)=delete
void * handle
dlopen library handle
Definition function.hpp:96
R operator()(Args... args) const
Invoke the loaded function.
Definition function.hpp:89
Function(char const *lib, char const *name)
Load a function from a named shared library.
Definition function.hpp:35
Fn fn
resolved function pointer
Definition function.hpp:97
Definition ast.hpp:14
Definition main.cpp:72