30 #ifndef _PYCPPWRAPPER_H_ 31 #define _PYCPPWRAPPER_H_ 40 #include <boost/locale/encoding_utf.hpp> 41 #include <boost/filesystem/path.hpp> 42 #include <boost/filesystem.hpp> 45 #if PY_MAJOR_VERSION < 3 46 #error "This file can only handle python >= 3" 52 inline PyObject* PyRun_String_func(
const char *str,
int start, PyObject *globals, PyObject *locals) {
return PyRun_String(str, start, globals, locals); }
54 #define PyRun_String PythonCpp::PyRun_String_func 57 inline int PyFloat_Check_func(PyObject *p) {
return PyFloat_Check(p); }
59 #define PyFloat_Check PythonCpp::PyFloat_Check_func 62 inline int PyFloat_AS_DOUBLE_func(PyObject *p) {
return PyFloat_AS_DOUBLE(p); }
63 #undef PyFloat_AS_DOUBLE 64 #define PyFloat_AS_DOUBLE PythonCpp::PyFloat_AS_DOUBLE_func 67 inline int PyBool_Check_func(PyObject *p) {
return PyBool_Check(p); }
69 #define PyBool_Check PythonCpp::PyBool_Check_func 72 inline int PyList_Check_func(PyObject *p) {
return PyList_Check(p); }
74 #define PyList_Check PythonCpp::PyList_Check_func 77 inline int PyObject_TypeCheck_func(PyObject *p, PyTypeObject *type) {
return PyObject_TypeCheck(p, type); }
78 #undef PyObject_TypeCheck 79 #define PyObject_TypeCheck PythonCpp::PyObject_TypeCheck_func 82 inline int PyLong_Check_func(PyObject *p) {
return PyLong_Check(p); }
84 #define PyLong_Check PythonCpp::PyLong_Check_func 87 inline int PyUnicode_Check_func(PyObject *p) {
return PyUnicode_Check(p); }
88 #undef PyUnicode_Check 89 #define PyUnicode_Check PythonCpp::PyUnicode_Check_func 94 constexpr
PyO() =
default;
95 explicit PyO(PyObject *src,
bool srcIsBorrowedRef=
false) : p(src) {
if(srcIsBorrowedRef) Py_XINCREF(p); }
96 PyO(
const PyO &r) : p(r.p) { Py_XINCREF(p); }
97 PyO(
PyO &&r) noexcept : p(r.p) { r.p=
nullptr; }
98 ~
PyO() { Py_XDECREF(p); }
99 PyO& operator=(
const PyO &r) { Py_XDECREF(p); p=r.p; Py_XINCREF(p);
return *
this; }
100 PyO& operator=(
PyO &&r) noexcept { Py_XDECREF(p); p=r.p; r.p=
nullptr;
return *
this; }
101 void reset() { Py_XDECREF(p); p=
nullptr; }
102 void reset(PyObject *src,
bool srcIsBorrowedRef=
false) { Py_XDECREF(p); p=src;
if(srcIsBorrowedRef) Py_XINCREF(p); }
103 void swap(
PyO &r) { PyObject *temp=p; p=r.p; r.p=temp; }
104 PyObject* get(
bool incRef=
false)
const {
if(incRef) Py_XINCREF(p);
return p; }
105 long use_count()
const {
return p ? Py_REFCNT(p) : 0; }
106 PyObject* operator->()
const {
return p; }
107 PyO& incRef() { Py_XINCREF(p);
return *
this; }
108 operator bool()
const {
return p!=
nullptr; }
110 PyObject *p{
nullptr};
113 inline bool operator==(
const PyO& l,
const PyO& r) {
return l.get()==r.get(); }
114 inline bool operator!=(
const PyO& l,
const PyO& r) {
return l.get()!=r.get(); }
115 inline bool operator< (
const PyO& l,
const PyO& r) {
return l.get()< r.get(); }
116 inline bool operator> (
const PyO& l,
const PyO& r) {
return l.get()> r.get(); }
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(); }
127 std::string getFile() {
return file; }
128 int getLine() {
return line; }
129 PyO getType() {
return type; }
130 PyO getValue() {
return value; }
131 PyO getTraceback() {
return traceback; }
132 inline const char* what()
const noexcept
override;
136 PyO type, value, traceback;
137 mutable std::string msg;
141 inline void checkPythonError() {
151 inline static type convert(
const T &r) {
158 inline static PyO convert(PyObject *r) {
160 throw std::runtime_error(
"Internal error: Expected python object but got NULL pointer and no python exception is set.");
162 throw std::runtime_error(
"Internal error: Expected python object but a python object with 0 refcount and no python exception is set.");
169 template<
typename Arg>
170 inline Arg convertArg(
const Arg &arg) {
174 inline PyObject* convertArg(
const PyO &o) {
175 if(o && o.use_count()<=0)
176 throw std::runtime_error(
"Internal error: access object with reference count <= 0. Check the source code.");
180 inline const char* convertArg(
const std::string &o) {
186 template<
typename PyRet,
typename... PyArgs,
typename... CallArgs>
187 inline typename MapRetType<PyRet>::type callPy(
const char *file,
int line, PyRet (*func)(PyArgs...), CallArgs&&... args) {
188 #if !defined(_WIN32) && !defined(NDEBUG) 190 int fpeExcept=fedisableexcept(FE_OVERFLOW | FE_INVALID | FE_OVERFLOW);
191 assert(fpeExcept!=-1);
193 PyRet ret=func(convertArg(std::forward<CallArgs>(args))...);
194 #if !defined(_WIN32) && !defined(NDEBUG) 195 assert(feenableexcept(fpeExcept)!=-1);
198 throw PythonException(file, line);
199 return MapRetType<PyRet>::convert(ret);
206 #define CALLPY(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__) 212 #define CALLPYB(...) PythonCpp::callPy(__FILE__, __LINE__, __VA_ARGS__).incRef() 218 inline void initializePython(
const boost::filesystem::path &main,
const std::string &pythonVersion,
219 const std::vector<boost::filesystem::path> &sysPathAppend={},
220 const std::vector<boost::filesystem::path> &possiblePrefix={}) {
221 boost::filesystem::path PYTHONHOME;
222 if(!getenv(
"PYTHONHOME")) {
223 for(
auto &p : possiblePrefix) {
224 if(boost::filesystem::is_directory(p/
"lib64"/(
"python"+pythonVersion)/
"encodings") ||
225 boost::filesystem::is_directory(p/
"lib"/(
"python"+pythonVersion)/
"encodings") ||
227 boost::filesystem::exists(p/
"bin"/
"python.exe") ||
228 boost::filesystem::exists(p/
"bin"/
"python3.exe") ||
229 boost::filesystem::exists(p/
"bin"/
"python.bat") ||
230 boost::filesystem::exists(p/
"bin"/
"python3.bat")
232 boost::filesystem::exists(p/
"bin"/
"python") ||
233 boost::filesystem::exists(p/
"bin"/
"python3")
240 if(!PYTHONHOME.empty()) {
242 static std::string PYTHONHOME_ENV(std::string(
"PYTHONHOME=")+PYTHONHOME.string());
243 putenv((
char*)PYTHONHOME_ENV.c_str());
247 static auto mainW=boost::locale::conv::utf_to_utf<wchar_t>(main.string());
250 #pragma GCC diagnostic push 251 #pragma GCC diagnostic ignored "-Wdeprecated-declarations" 253 Py_SetProgramName(const_cast<wchar_t*>(mainW.c_str()));
255 #pragma GCC diagnostic pop 260 boost::filesystem::path dllDir(
"bin");
261 std::string pathsep(
";");
263 boost::filesystem::path dllDir(
"lib");
264 std::string pathsep(
":");
266 if(!PYTHONHOME.empty()) {
267 #if _WIN32 && PY_MAJOR_VERSION==3 && PY_MINOR_VERSION>=8 268 PyO os=CALLPY(PyImport_ImportModule,
"os");
269 PyO os_add_dll_directory=CALLPY(PyObject_GetAttrString, os,
"add_dll_directory");
270 PyO arg(CALLPY(PyTuple_New, 1));
271 PyO libdir(CALLPY(PyUnicode_FromString, (PYTHONHOME/dllDir).
string()));
272 CALLPY(PyTuple_SetItem, arg, 0, libdir.incRef());
273 CALLPY(PyObject_CallObject, os_add_dll_directory, arg);
276 std::string PATH_OLD(getenv(
"PATH"));
277 static std::string PATH_ENV(
"PATH="+PATH_OLD+pathsep+(PYTHONHOME/dllDir).
string());
278 putenv((
char*)PATH_ENV.c_str());
283 PyO sysPath(CALLPYB(PySys_GetObject, const_cast<char*>(
"path")));
284 for(
auto &p : sysPathAppend)
285 CALLPY(PyList_Append, sysPath, CALLPY(PyUnicode_FromString, p.string()));
289 PythonException::PythonException(
const char *file_,
int line_) : file(file_), line(line_) {
291 if(!PyErr_Occurred())
292 throw std::runtime_error(
"Internal error: PythonException object created but no python error occured.");
294 PyObject *type_, *value_, *traceback_;
295 PyErr_Fetch(&type_, &value_, &traceback_);
298 traceback=PyO(traceback_);
301 const inline char* PythonException::what() const noexcept {
306 PyObject *savedstderr=PySys_GetObject(const_cast<char*>(
"stderr"));
308 return "Unable to create Python error message: no sys.stderr available.";
309 PyObject *io=PyImport_ImportModule(
"io");
311 return "Unable to create Python error message: cannot load io module.";
312 PyObject *fileIO=PyObject_GetAttrString(io,
"StringIO");
314 return "Unable to create Python error message: cannot get in memory file class.";
316 PyObject *buf=PyObject_CallObject(fileIO,
nullptr);
319 return "Unable to create Python error message: cannot create new in memory file instance";
320 if(PySys_SetObject(const_cast<char*>(
"stderr"), buf)!=0)
321 return "Unable to create Python error message: cannot redirect stderr";
323 PyErr_Restore(type.get(), value.get(), traceback.get());
324 Py_XINCREF(type.get());
325 Py_XINCREF(value.get());
326 Py_XINCREF(traceback.get());
330 if(PySys_SetObject(const_cast<char*>(
"stderr"), savedstderr)!=0)
331 return "Unable to create Python error message: cannot revert redirect stderr";
333 PyObject *getvalue=PyObject_GetAttrString(buf,
"getvalue");
335 return "Unable to create Python error message: cannot get getvalue attribute";
336 PyObject *pybufstr=PyObject_CallObject(getvalue,
nullptr);
338 return "Unable to create Python error message: cannot get string from in memory file output";
341 std::string str=PyUnicode_AsUTF8(pybufstr);
343 return "Unable to create Python error message: cannot get c string";
345 std::stringstream strstr;
346 strstr<<
"Python exception";
348 strstr<<
" at "<<file<<
":"<<line;
349 strstr<<
":"<<std::endl<<str;
355 template<
typename... Args>
356 PyO Py_BuildValue_(
const char *format, Args&&... args) {
357 return PyO(Py_BuildValue(format, convertArg(std::forward<Args>(args))...));
Definition: pycppwrapper.h:92
Definition: pycppwrapper.h:123
Definition: pycppwrapper.h:149