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 
42 #if PY_MAJOR_VERSION < 3
43  #error "This file can only handle python >= 3"
44 #endif
45 
46 namespace PythonCpp {
47 
48 // initialize python giving main as program name to python
49 inline void initializePython(const std::string &main) {
50  static auto mainW=boost::locale::conv::utf_to_utf<wchar_t>(main);
51  Py_SetProgramName(const_cast<wchar_t*>(mainW.c_str()));
52  Py_InitializeEx(0);
53 }
54 
55 // make PyRun_String a function
56 inline PyObject* PyRun_String_func(const char *str, int start, PyObject *globals, PyObject *locals) { return PyRun_String(str, start, globals, locals); }
57 #undef PyRun_String
58 #define PyRun_String PythonCpp::PyRun_String_func
59 
60 // make PyFloat_Check a function
61 inline int PyFloat_Check_func(PyObject *p) { return PyFloat_Check(p); }
62 #undef PyFloat_Check
63 #define PyFloat_Check PythonCpp::PyFloat_Check_func
64 
65 // make PyFloat_AS_DOUBLE a function
66 inline int PyFloat_AS_DOUBLE_func(PyObject *p) { return PyFloat_AS_DOUBLE(p); }
67 #undef PyFloat_AS_DOUBLE
68 #define PyFloat_AS_DOUBLE PythonCpp::PyFloat_AS_DOUBLE_func
69 
70 // make PyBool_Check a function
71 inline int PyBool_Check_func(PyObject *p) { return PyBool_Check(p); }
72 #undef PyBool_Check
73 #define PyBool_Check PythonCpp::PyBool_Check_func
74 
75 // make PyList_Check a function
76 inline int PyList_Check_func(PyObject *p) { return PyList_Check(p); }
77 #undef PyList_Check
78 #define PyList_Check PythonCpp::PyList_Check_func
79 
80 // make PyObject_TypeCheck a function
81 inline int PyObject_TypeCheck_func(PyObject *p, PyTypeObject *type) { return PyObject_TypeCheck(p, type); }
82 #undef PyObject_TypeCheck
83 #define PyObject_TypeCheck PythonCpp::PyObject_TypeCheck_func
84 
85 // make PyLong_Check a function
86 inline int PyLong_Check_func(PyObject *p) { return PyLong_Check(p); }
87 #undef PyLong_Check
88 #define PyLong_Check PythonCpp::PyLong_Check_func
89 
90 // make PyUnicode_Check a function
91 inline int PyUnicode_Check_func(PyObject *p) { return PyUnicode_Check(p); }
92 #undef PyUnicode_Check
93 #define PyUnicode_Check PythonCpp::PyUnicode_Check_func
94 
95 // we use this for python object for c++ reference counting
96 class PyO {
97  public:
98  constexpr PyO() = default;
99  explicit PyO(PyObject *src, bool srcIsBorrowedRef=false) : p(src) { if(srcIsBorrowedRef) Py_XINCREF(p); } // use srcIsBorrowedRef=true if src is a borrowed reference
100  PyO(const PyO &r) : p(r.p) { Py_XINCREF(p); }
101  PyO(PyO &&r) : p(r.p) { r.p=nullptr; }
102  ~PyO() { Py_XDECREF(p); }
103  PyO& operator=(const PyO &r) { Py_XDECREF(p); p=r.p; Py_XINCREF(p); return *this; }
104  PyO& operator=(PyO &&r) { Py_XDECREF(p); p=r.p; r.p=nullptr; return *this; }
105  void reset() { Py_XDECREF(p); p=nullptr; }
106  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
107  void swap(PyO &r) { PyObject *temp=p; p=r.p; r.p=temp; }
108  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
109  long use_count() const { return p ? Py_REFCNT(p) : 0; }
110  PyObject* operator->() const { return p; }
111  PyO& incRef() { Py_XINCREF(p); return *this; } // use if the caller steals a reference of the returned PyObject
112  operator bool() const { return p!=nullptr; }
113  protected:
114  PyObject *p{nullptr};
115 };
116 
117 inline bool operator==(const PyO& l, const PyO& r) { return l.get()==r.get(); }
118 inline bool operator!=(const PyO& l, const PyO& r) { return l.get()!=r.get(); }
119 inline bool operator< (const PyO& l, const PyO& r) { return l.get()< r.get(); }
120 inline bool operator> (const PyO& l, const PyO& r) { return l.get()> r.get(); }
121 inline bool operator<=(const PyO& l, const PyO& r) { return l.get()<=r.get(); }
122 inline bool operator>=(const PyO& l, const PyO& r) { return l.get()>=r.get(); }
123 
124 // A Python error exception object.
125 // Stores the file and line number of the C++ file where the error occured.
126 // Stores also the Python error objects type, value and traceback.
127 class PythonException : public std::exception {
128  public:
129  inline PythonException(const char *file_, int line_);
130  ~PythonException() noexcept override = default;
131  std::string getFile() { return file; }
132  int getLine() { return line; }
133  PyO getType() { return type; }
134  PyO getValue() { return value; }
135  PyO getTraceback() { return traceback; }
136  inline const char* what() const noexcept override;
137  private:
138  std::string file;
139  int line;
140  PyO type, value, traceback;
141  mutable std::string msg;
142 };
143 
144 // check for a python exception and throw a PythonException if one exists
145 inline void checkPythonError() {
146  if(PyErr_Occurred())
147  throw PythonException("", 0);
148 }
149 
150 // helper struct to map the return type of the callPy function
151 // default: map to the same type
152 template<typename T>
153 struct MapRetType {
154  typedef T type;
155  inline static type convert(const T &r) {
156  return r;
157  }
158 };
159 // specialization: map PyObject* to PyO
160 template<> struct MapRetType<PyObject*> {
161  typedef PyO type;
162  inline static PyO convert(PyObject *r) {
163  if(!r)
164  throw std::runtime_error("Internal error: Expected python object but got NULL pointer and no python exception is set.");
165  if(Py_REFCNT(r)<=0)
166  throw std::runtime_error("Internal error: Expected python object but a python object with 0 refcount and no python exception is set.");
167  return PyO(r);
168  }
169 };
170 
171 // helper function to map the argument types of the callPy function
172 // default: map to the same type
173 template<typename Arg>
174 inline Arg convertArg(const Arg &arg) {
175  return arg;
176 }
177 // specialization:: map PyO to PyObject*
178 inline PyObject* convertArg(const PyO &o) {
179  if(o && o.use_count()<=0)
180  throw std::runtime_error("Internal error: access object with reference count <= 0. Check the source code.");
181  return o.get();
182 }
183 // specialization:: map std::string to const char*
184 inline const char* convertArg(const std::string &o) {
185  return o.c_str();
186 }
187 
188 // Call Python function func with arguments args.
189 // Use the macro CALLPY or CALLPYB, see below.
190 template<typename PyRet, typename... PyArgs, typename... CallArgs>
191 inline typename MapRetType<PyRet>::type callPy(const char *file, int line, PyRet (*func)(PyArgs...), CallArgs&&... args) {
192  PyRet ret=func(convertArg(std::forward<CallArgs>(args))...);
193  if(PyErr_Occurred())
194  throw PythonException(file, line);
195  return MapRetType<PyRet>::convert(ret);
196 }
197 
198 // Macro to call callPy(...)
199 // Use this macro to call a python function returning a new reference to a python object or any other return type.
200 // Note, if the python function steals a reference of any of this arguments you have to call arg.incRef() on
201 // each such arguments.
202 #define CALLPY(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__)
203 
204 // Macro to call callPy(...).incRef()
205 // Use this macro to call a python function returning a borrowed reference to a python object.
206 // Note, if the python function steals a reference of any of this arguments you have to call arg.incRef() on
207 // each such arguments.
208 #define CALLPYB(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__).incRef()
209 
210 // c++ PythonException exception with the content of a python exception
211 PythonException::PythonException(const char *file_, int line_) : file(file_), line(line_) {
212  // fetch if error has occured
213  if(!PyErr_Occurred())
214  throw std::runtime_error("Internal error: PythonException object created but no python error occured.");
215  // fetch error objects and save objects
216  PyObject *type_, *value_, *traceback_;
217  PyErr_Fetch(&type_, &value_, &traceback_);
218  type=PyO(type_);
219  value=PyO(value_);
220  traceback=PyO(traceback_);
221 }
222 
223 const inline char* PythonException::what() const noexcept {
224  if(!msg.empty())
225  return msg.c_str();
226 
227  // redirect stderr
228  PyObject *savedstderr=PySys_GetObject(const_cast<char*>("stderr"));
229  if(!savedstderr)
230  return "Unable to create Python error message: no sys.stderr available.";
231  PyObject *io=PyImport_ImportModule("io");
232  if(!io)
233  return "Unable to create Python error message: cannot load io module.";
234  PyObject *fileIO=PyObject_GetAttrString(io, "StringIO"); // sys.stderr is a file in text mode
235  if(!fileIO)
236  return "Unable to create Python error message: cannot get in memory file class.";
237  Py_DECREF(io);
238  PyObject *buf=PyObject_CallObject(fileIO, nullptr);
239  Py_DECREF(fileIO);
240  if(!buf)
241  return "Unable to create Python error message: cannot create new in memory file instance";
242  if(PySys_SetObject(const_cast<char*>("stderr"), buf)!=0)
243  return "Unable to create Python error message: cannot redirect stderr";
244  // restore error
245  PyErr_Restore(type.get(), value.get(), traceback.get());
246  Py_XINCREF(type.get());
247  Py_XINCREF(value.get());
248  Py_XINCREF(traceback.get());
249  // print to redirected stderr
250  PyErr_Print();
251  // unredirect stderr
252  if(PySys_SetObject(const_cast<char*>("stderr"), savedstderr)!=0)
253  return "Unable to create Python error message: cannot revert redirect stderr";
254  // get redirected output as string
255  PyObject *getvalue=PyObject_GetAttrString(buf, "getvalue");
256  if(!getvalue)
257  return "Unable to create Python error message: cannot get getvalue attribute";
258  PyObject *pybufstr=PyObject_CallObject(getvalue, nullptr);
259  if(!pybufstr)
260  return "Unable to create Python error message: cannot get string from in memory file output";
261  Py_DECREF(getvalue);
262  Py_DECREF(buf);
263  std::string str=PyUnicode_AsUTF8(pybufstr); // sys.stderr is a file in text mode
264  if(PyErr_Occurred())
265  return "Unable to create Python error message: cannot get c string";
266  Py_DECREF(pybufstr);
267  std::stringstream strstr;
268  strstr<<"Python exception";
269  if(!file.empty())
270  strstr<<" at "<<file<<":"<<line;
271  strstr<<":"<<std::endl<<str;
272  msg=strstr.str();
273  return msg.c_str();
274 }
275 
276 // a Py_BuildValue variant working like called with CALLPY
277 template<typename... Args>
278 PyO Py_BuildValue_(const char *format, Args&&... args) {
279  return PyO(Py_BuildValue(format, convertArg(std::forward<Args>(args))...));
280 }
281 
282 }
283 
284 #endif
Definition: pycppwrapper.h:96
Definition: pycppwrapper.h:127
Definition: pycppwrapper.h:153