-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpy_functions.h
90 lines (67 loc) · 1.65 KB
/
py_functions.h
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#ifndef PY_FUNCTIONS_H_
#define PY_FUNCTIONS_H_
#include <string>
#include <stdexcept>
// pxd: from libcpp.string cimport string
namespace test {
namespace py_functions {
void throw_py_err_as_cpp_exc();
template<typename ReturnType, typename ...ArgTypes>
class PyFunc {
private:
ReturnType (*ptr)(ArgTypes ...) = nullptr;
public:
void operator =(ReturnType (*ptr)(ArgTypes ...)) {
this->ptr = ptr;
}
ReturnType operator ()(ArgTypes ...args) {
if (this->ptr == nullptr) {
throw std::runtime_error("function ptr is nullptr");
}
ReturnType result = this->ptr(std::forward<ArgTypes>(args)...);
throw_py_err_as_cpp_exc();
return result;
}
};
template<typename ...ArgTypes>
class PyFunc<void, ArgTypes ...> {
private:
void (*ptr)(ArgTypes ...) = nullptr;
public:
void operator =(void (*ptr)(ArgTypes ...)) {
this->ptr = ptr;
}
void operator ()(ArgTypes ...args) {
if (this->ptr == nullptr) {
throw std::runtime_error("function ptr is nullptr");
}
this->ptr(std::forward<ArgTypes>(args)...);
throw_py_err_as_cpp_exc();
}
};
/**
* prints the square of a given number, using python .format() and test::square()
*
* pxd: void (*print_square)(int) except*
*/
extern PyFunc<void, int> print_square;
/**
* launches the interactive console
*
* pxd: void (*interact)() except*
*/
extern PyFunc<void> interact;
/**
* test function that raises a Python exception
*
* pxd: int (*exctest)(int) except*
*/
extern PyFunc<int, int> exctest;
/**
* invokes all string callbacks
*
* pxd: string (*invoke_callbacks)(string) except*
*/
extern PyFunc<std::string, std::string> invoke_callbacks;
}} // namespace test::py_functions
#endif