-
Notifications
You must be signed in to change notification settings - Fork 1
/
py_functions.cpp
62 lines (42 loc) · 1.19 KB
/
py_functions.cpp
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
#include "py_functions.h"
#include <iostream>
#include <string>
#include <Python.h>
using namespace std;
namespace test {
namespace py_functions {
std::string repr(PyObject *obj) {
PyObject *str = PyObject_Repr(obj);
PyObject *bytes = PyUnicode_AsEncodedString(str, "utf-8", "Error ~");
std::string result = PyBytes_AS_STRING(bytes);
Py_XDECREF(bytes);
Py_XDECREF(str);
return result;
}
std::string str(PyObject *obj) {
PyObject *str = PyObject_Str(obj);
PyObject *bytes = PyUnicode_AsEncodedString(str, "utf-8", "Error ~");
std::string result = PyBytes_AS_STRING(bytes);
Py_XDECREF(bytes);
Py_XDECREF(str);
return result;
}
void throw_py_err_as_cpp_exc() {
if (!PyErr_Occurred()) {
return;
}
PyObject *type = NULL, *value = NULL, *traceback = NULL;
PyErr_Fetch(&type, &value, &traceback);
std::string typerepr = str(type);
std::string valrepr = str(value);
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
PyErr_Clear();
throw runtime_error("python exception: " + typerepr + ": " + valrepr);
}
PyFunc<void, int> print_square;
PyFunc<void> interact;
PyFunc<int, int> exctest;
PyFunc<std::string, std::string> invoke_callbacks;
}} // namespace test::py_functions