30 #ifndef _PYCPPWRAPPER_H_ 31 #define _PYCPPWRAPPER_H_ 40 #include <boost/locale/encoding_utf.hpp> 43 #if PY_MAJOR_VERSION < 3 44 #error "This file can only handle python >= 3" 50 inline void initializePython(
const std::string &main) {
51 static auto mainW=boost::locale::conv::utf_to_utf<wchar_t>(main);
54 #pragma GCC diagnostic push 55 #pragma GCC diagnostic ignored "-Wdeprecated-declarations" 57 Py_SetProgramName(const_cast<wchar_t*>(mainW.c_str()));
59 #pragma GCC diagnostic pop 65 inline PyObject* PyRun_String_func(
const char *str,
int start, PyObject *globals, PyObject *locals) {
return PyRun_String(str, start, globals, locals); }
67 #define PyRun_String PythonCpp::PyRun_String_func 70 inline int PyFloat_Check_func(PyObject *p) {
return PyFloat_Check(p); }
72 #define PyFloat_Check PythonCpp::PyFloat_Check_func 75 inline int PyFloat_AS_DOUBLE_func(PyObject *p) {
return PyFloat_AS_DOUBLE(p); }
76 #undef PyFloat_AS_DOUBLE 77 #define PyFloat_AS_DOUBLE PythonCpp::PyFloat_AS_DOUBLE_func 80 inline int PyBool_Check_func(PyObject *p) {
return PyBool_Check(p); }
82 #define PyBool_Check PythonCpp::PyBool_Check_func 85 inline int PyList_Check_func(PyObject *p) {
return PyList_Check(p); }
87 #define PyList_Check PythonCpp::PyList_Check_func 90 inline int PyObject_TypeCheck_func(PyObject *p, PyTypeObject *type) {
return PyObject_TypeCheck(p, type); }
91 #undef PyObject_TypeCheck 92 #define PyObject_TypeCheck PythonCpp::PyObject_TypeCheck_func 95 inline int PyLong_Check_func(PyObject *p) {
return PyLong_Check(p); }
97 #define PyLong_Check PythonCpp::PyLong_Check_func 100 inline int PyUnicode_Check_func(PyObject *p) {
return PyUnicode_Check(p); }
101 #undef PyUnicode_Check 102 #define PyUnicode_Check PythonCpp::PyUnicode_Check_func 107 constexpr
PyO() =
default;
108 explicit PyO(PyObject *src,
bool srcIsBorrowedRef=
false) : p(src) {
if(srcIsBorrowedRef) Py_XINCREF(p); }
109 PyO(
const PyO &r) : p(r.p) { Py_XINCREF(p); }
110 PyO(
PyO &&r) noexcept : p(r.p) { r.p=
nullptr; }
111 ~
PyO() { Py_XDECREF(p); }
112 PyO& operator=(
const PyO &r) { Py_XDECREF(p); p=r.p; Py_XINCREF(p);
return *
this; }
113 PyO& operator=(
PyO &&r) noexcept { Py_XDECREF(p); p=r.p; r.p=
nullptr;
return *
this; }
114 void reset() { Py_XDECREF(p); p=
nullptr; }
115 void reset(PyObject *src,
bool srcIsBorrowedRef=
false) { Py_XDECREF(p); p=src;
if(srcIsBorrowedRef) Py_XINCREF(p); }
116 void swap(
PyO &r) { PyObject *temp=p; p=r.p; r.p=temp; }
117 PyObject* get(
bool incRef=
false)
const {
if(incRef) Py_XINCREF(p);
return p; }
118 long use_count()
const {
return p ? Py_REFCNT(p) : 0; }
119 PyObject* operator->()
const {
return p; }
120 PyO& incRef() { Py_XINCREF(p);
return *
this; }
121 operator bool()
const {
return p!=
nullptr; }
123 PyObject *p{
nullptr};
126 inline bool operator==(
const PyO& l,
const PyO& r) {
return l.get()==r.get(); }
127 inline bool operator!=(
const PyO& l,
const PyO& r) {
return l.get()!=r.get(); }
128 inline bool operator< (
const PyO& l,
const PyO& r) {
return l.get()< r.get(); }
129 inline bool operator> (
const PyO& l,
const PyO& r) {
return l.get()> r.get(); }
130 inline bool operator<=(
const PyO& l,
const PyO& r) {
return l.get()<=r.get(); }
131 inline bool operator>=(
const PyO& l,
const PyO& r) {
return l.get()>=r.get(); }
140 std::string getFile() {
return file; }
141 int getLine() {
return line; }
142 PyO getType() {
return type; }
143 PyO getValue() {
return value; }
144 PyO getTraceback() {
return traceback; }
145 inline const char* what()
const noexcept
override;
149 PyO type, value, traceback;
150 mutable std::string msg;
154 inline void checkPythonError() {
164 inline static type convert(
const T &r) {
171 inline static PyO convert(PyObject *r) {
173 throw std::runtime_error(
"Internal error: Expected python object but got NULL pointer and no python exception is set.");
175 throw std::runtime_error(
"Internal error: Expected python object but a python object with 0 refcount and no python exception is set.");
182 template<
typename Arg>
183 inline Arg convertArg(
const Arg &arg) {
187 inline PyObject* convertArg(
const PyO &o) {
188 if(o && o.use_count()<=0)
189 throw std::runtime_error(
"Internal error: access object with reference count <= 0. Check the source code.");
193 inline const char* convertArg(
const std::string &o) {
199 template<
typename PyRet,
typename... PyArgs,
typename... CallArgs>
200 inline typename MapRetType<PyRet>::type callPy(
const char *file,
int line, PyRet (*func)(PyArgs...), CallArgs&&... args) {
201 #if !defined(_WIN32) && !defined(NDEBUG) 203 int fpeExcept=fedisableexcept(FE_OVERFLOW | FE_INVALID | FE_OVERFLOW);
204 assert(fpeExcept!=-1);
206 PyRet ret=func(convertArg(std::forward<CallArgs>(args))...);
207 #if !defined(_WIN32) && !defined(NDEBUG) 208 assert(feenableexcept(fpeExcept)!=-1);
211 throw PythonException(file, line);
212 return MapRetType<PyRet>::convert(ret);
219 #define CALLPY(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__) 225 #define CALLPYB(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__).incRef() 228 PythonException::PythonException(
const char *file_,
int line_) : file(file_), line(line_) {
230 if(!PyErr_Occurred())
231 throw std::runtime_error(
"Internal error: PythonException object created but no python error occured.");
233 PyObject *type_, *value_, *traceback_;
234 PyErr_Fetch(&type_, &value_, &traceback_);
237 traceback=PyO(traceback_);
240 const inline char* PythonException::what() const noexcept {
245 PyObject *savedstderr=PySys_GetObject(const_cast<char*>(
"stderr"));
247 return "Unable to create Python error message: no sys.stderr available.";
248 PyObject *io=PyImport_ImportModule(
"io");
250 return "Unable to create Python error message: cannot load io module.";
251 PyObject *fileIO=PyObject_GetAttrString(io,
"StringIO");
253 return "Unable to create Python error message: cannot get in memory file class.";
255 PyObject *buf=PyObject_CallObject(fileIO,
nullptr);
258 return "Unable to create Python error message: cannot create new in memory file instance";
259 if(PySys_SetObject(const_cast<char*>(
"stderr"), buf)!=0)
260 return "Unable to create Python error message: cannot redirect stderr";
262 PyErr_Restore(type.get(), value.get(), traceback.get());
263 Py_XINCREF(type.get());
264 Py_XINCREF(value.get());
265 Py_XINCREF(traceback.get());
269 if(PySys_SetObject(const_cast<char*>(
"stderr"), savedstderr)!=0)
270 return "Unable to create Python error message: cannot revert redirect stderr";
272 PyObject *getvalue=PyObject_GetAttrString(buf,
"getvalue");
274 return "Unable to create Python error message: cannot get getvalue attribute";
275 PyObject *pybufstr=PyObject_CallObject(getvalue,
nullptr);
277 return "Unable to create Python error message: cannot get string from in memory file output";
280 std::string str=PyUnicode_AsUTF8(pybufstr);
282 return "Unable to create Python error message: cannot get c string";
284 std::stringstream strstr;
285 strstr<<
"Python exception";
287 strstr<<
" at "<<file<<
":"<<line;
288 strstr<<
":"<<std::endl<<str;
294 template<
typename... Args>
295 PyO Py_BuildValue_(
const char *format, Args&&... args) {
296 return PyO(Py_BuildValue(format, convertArg(std::forward<Args>(args))...));
Definition: pycppwrapper.h:105
Definition: pycppwrapper.h:136
Definition: pycppwrapper.h:162