mbxmlutils  1.3.0
Multi-Body XML Utils
pycppwrapper.h
1 /*
2  * Author: Markus Friedrich
3  *
4  * This file is free and unencumbered software released into the public domain.
5  *
6  * Anyone is free to copy, modify, publish, use, compile, sell, or
7  * distribute this software, either in source code form or as a compiled
8  * binary, for any purpose, commercial or non-commercial, and by any
9  * means.
10  *
11  * In jurisdictions that recognize copyright laws, the author or authors
12  * of this software dedicate any and all copyright interest in the
13  * software to the public domain. We make this dedication for the benefit
14  * of the public at large and to the detriment of our heirs and
15  * successors. We intend this dedication to be an overt act of
16  * relinquishment in perpetuity of all present and future rights to this
17  * software under copyright law.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
23  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
24  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25  * OTHER DEALINGS IN THE SOFTWARE.
26  *
27  * For more information, please refer to <http://unlicense.org/>
28  */
29 
30 #ifndef _PYCPPWRAPPER_H_
31 #define _PYCPPWRAPPER_H_
32 
33 #include <Python.h>
34 #include <string>
35 #include <vector>
36 #include <stdexcept>
37 #include <memory>
38 #include <sstream>
39 #include <memory>
40 #include <boost/locale/encoding_utf.hpp> // gcc does not support <codecvt> yet
41 #include <cfenv>
42 
43 #if PY_MAJOR_VERSION < 3
44  #error "This file can only handle python >= 3"
45 #endif
46 
47 namespace PythonCpp {
48 
49 // initialize python giving main as program name to python
50 inline void initializePython(const std::string &main) {
51  static auto mainW=boost::locale::conv::utf_to_utf<wchar_t>(main);
52  #if __GNUC__ >= 11
53  // python >= 3.8 has deprecated this call
54  #pragma GCC diagnostic push
55  #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
56  #endif
57  Py_SetProgramName(const_cast<wchar_t*>(mainW.c_str()));
58  #if __GNUC__ >= 11
59  #pragma GCC diagnostic pop
60  #endif
61  Py_InitializeEx(0);
62 }
63 
64 // make PyRun_String a function
65 inline PyObject* PyRun_String_func(const char *str, int start, PyObject *globals, PyObject *locals) { return PyRun_String(str, start, globals, locals); }
66 #undef PyRun_String
67 #define PyRun_String PythonCpp::PyRun_String_func
68 
69 // make PyFloat_Check a function
70 inline int PyFloat_Check_func(PyObject *p) { return PyFloat_Check(p); }
71 #undef PyFloat_Check
72 #define PyFloat_Check PythonCpp::PyFloat_Check_func
73 
74 // make PyFloat_AS_DOUBLE a function
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
78 
79 // make PyBool_Check a function
80 inline int PyBool_Check_func(PyObject *p) { return PyBool_Check(p); }
81 #undef PyBool_Check
82 #define PyBool_Check PythonCpp::PyBool_Check_func
83 
84 // make PyList_Check a function
85 inline int PyList_Check_func(PyObject *p) { return PyList_Check(p); }
86 #undef PyList_Check
87 #define PyList_Check PythonCpp::PyList_Check_func
88 
89 // make PyObject_TypeCheck a function
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
93 
94 // make PyLong_Check a function
95 inline int PyLong_Check_func(PyObject *p) { return PyLong_Check(p); }
96 #undef PyLong_Check
97 #define PyLong_Check PythonCpp::PyLong_Check_func
98 
99 // make PyUnicode_Check a function
100 inline int PyUnicode_Check_func(PyObject *p) { return PyUnicode_Check(p); }
101 #undef PyUnicode_Check
102 #define PyUnicode_Check PythonCpp::PyUnicode_Check_func
103 
104 // we use this for python object for c++ reference counting
105 class PyO {
106  public:
107  constexpr PyO() = default;
108  explicit PyO(PyObject *src, bool srcIsBorrowedRef=false) : p(src) { if(srcIsBorrowedRef) Py_XINCREF(p); } // use srcIsBorrowedRef=true if src is a borrowed reference
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); } // use srcIsBorrowedRef=true if src is a borrowed reference
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; } // use incRef=true if the caller steals a reference of the returned PyObject
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; } // use if the caller steals a reference of the returned PyObject
121  operator bool() const { return p!=nullptr; }
122  protected:
123  PyObject *p{nullptr};
124 };
125 
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(); }
132 
133 // A Python error exception object.
134 // Stores the file and line number of the C++ file where the error occured.
135 // Stores also the Python error objects type, value and traceback.
136 class PythonException : public std::exception {
137  public:
138  inline PythonException(const char *file_, int line_);
139  ~PythonException() noexcept override = default;
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;
146  private:
147  std::string file;
148  int line;
149  PyO type, value, traceback;
150  mutable std::string msg;
151 };
152 
153 // check for a python exception and throw a PythonException if one exists
154 inline void checkPythonError() {
155  if(PyErr_Occurred())
156  throw PythonException("", 0);
157 }
158 
159 // helper struct to map the return type of the callPy function
160 // default: map to the same type
161 template<typename T>
162 struct MapRetType {
163  using type = T;
164  inline static type convert(const T &r) {
165  return r;
166  }
167 };
168 // specialization: map PyObject* to PyO
169 template<> struct MapRetType<PyObject*> {
170  using type = PyO;
171  inline static PyO convert(PyObject *r) {
172  if(!r)
173  throw std::runtime_error("Internal error: Expected python object but got NULL pointer and no python exception is set.");
174  if(Py_REFCNT(r)<=0)
175  throw std::runtime_error("Internal error: Expected python object but a python object with 0 refcount and no python exception is set.");
176  return PyO(r);
177  }
178 };
179 
180 // helper function to map the argument types of the callPy function
181 // default: map to the same type
182 template<typename Arg>
183 inline Arg convertArg(const Arg &arg) {
184  return arg;
185 }
186 // specialization:: map PyO to PyObject*
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.");
190  return o.get();
191 }
192 // specialization:: map std::string to const char*
193 inline const char* convertArg(const std::string &o) {
194  return o.c_str();
195 }
196 
197 // Call Python function func with arguments args.
198 // Use the macro CALLPY or CALLPYB, see below.
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)
202  // sympy/numpy/others may generate FPEs during calls -> disable FPE exceptions during load
203  int fpeExcept=fedisableexcept(FE_OVERFLOW | FE_INVALID | FE_OVERFLOW);
204  assert(fpeExcept!=-1);
205 #endif
206  PyRet ret=func(convertArg(std::forward<CallArgs>(args))...);
207 #if !defined(_WIN32) && !defined(NDEBUG)
208  assert(feenableexcept(fpeExcept)!=-1);
209 #endif
210  if(PyErr_Occurred())
211  throw PythonException(file, line);
212  return MapRetType<PyRet>::convert(ret);
213 }
214 
215 // Macro to call callPy(...)
216 // Use this macro to call a python function returning a new reference to a python object or any other return type.
217 // Note, if the python function steals a reference of any of this arguments you have to call arg.incRef() on
218 // each such arguments.
219 #define CALLPY(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__)
220 
221 // Macro to call callPy(...).incRef()
222 // Use this macro to call a python function returning a borrowed reference to a python object.
223 // Note, if the python function steals a reference of any of this arguments you have to call arg.incRef() on
224 // each such arguments.
225 #define CALLPYB(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__).incRef()
226 
227 // c++ PythonException exception with the content of a python exception
228 PythonException::PythonException(const char *file_, int line_) : file(file_), line(line_) {
229  // fetch if error has occured
230  if(!PyErr_Occurred())
231  throw std::runtime_error("Internal error: PythonException object created but no python error occured.");
232  // fetch error objects and save objects
233  PyObject *type_, *value_, *traceback_;
234  PyErr_Fetch(&type_, &value_, &traceback_);
235  type=PyO(type_);
236  value=PyO(value_);
237  traceback=PyO(traceback_);
238 }
239 
240 const inline char* PythonException::what() const noexcept {
241  if(!msg.empty())
242  return msg.c_str();
243 
244  // redirect stderr
245  PyObject *savedstderr=PySys_GetObject(const_cast<char*>("stderr"));
246  if(!savedstderr)
247  return "Unable to create Python error message: no sys.stderr available.";
248  PyObject *io=PyImport_ImportModule("io");
249  if(!io)
250  return "Unable to create Python error message: cannot load io module.";
251  PyObject *fileIO=PyObject_GetAttrString(io, "StringIO"); // sys.stderr is a file in text mode
252  if(!fileIO)
253  return "Unable to create Python error message: cannot get in memory file class.";
254  Py_DECREF(io);
255  PyObject *buf=PyObject_CallObject(fileIO, nullptr);
256  Py_DECREF(fileIO);
257  if(!buf)
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";
261  // restore error
262  PyErr_Restore(type.get(), value.get(), traceback.get());
263  Py_XINCREF(type.get());
264  Py_XINCREF(value.get());
265  Py_XINCREF(traceback.get());
266  // print to redirected stderr
267  PyErr_Print();
268  // unredirect stderr
269  if(PySys_SetObject(const_cast<char*>("stderr"), savedstderr)!=0)
270  return "Unable to create Python error message: cannot revert redirect stderr";
271  // get redirected output as string
272  PyObject *getvalue=PyObject_GetAttrString(buf, "getvalue");
273  if(!getvalue)
274  return "Unable to create Python error message: cannot get getvalue attribute";
275  PyObject *pybufstr=PyObject_CallObject(getvalue, nullptr);
276  if(!pybufstr)
277  return "Unable to create Python error message: cannot get string from in memory file output";
278  Py_DECREF(getvalue);
279  Py_DECREF(buf);
280  std::string str=PyUnicode_AsUTF8(pybufstr); // sys.stderr is a file in text mode
281  if(PyErr_Occurred())
282  return "Unable to create Python error message: cannot get c string";
283  Py_DECREF(pybufstr);
284  std::stringstream strstr;
285  strstr<<"Python exception";
286  if(!file.empty())
287  strstr<<" at "<<file<<":"<<line;
288  strstr<<":"<<std::endl<<str;
289  msg=strstr.str();
290  return msg.c_str();
291 }
292 
293 // a Py_BuildValue variant working like called with CALLPY
294 template<typename... Args>
295 PyO Py_BuildValue_(const char *format, Args&&... args) {
296  return PyO(Py_BuildValue(format, convertArg(std::forward<Args>(args))...));
297 }
298 
299 }
300 
301 #endif
Definition: pycppwrapper.h:105
Definition: pycppwrapper.h:136
Definition: pycppwrapper.h:162