Go to the documentation of this file.00001 #ifndef TF2_PY_PYTHON_COMPAT_H
00002 #define TF2_PY_PYTHON_COMPAT_H
00003
00004 #include <Python.h>
00005
00006 #include <string>
00007
00008 inline PyObject *stringToPython(const std::string &input)
00009 {
00010 #if PY_MAJOR_VERSION >= 3
00011 return PyUnicode_FromStringAndSize(input.c_str(), input.size());
00012 #else
00013 return PyString_FromStringAndSize(input.c_str(), input.size());
00014 #endif
00015 }
00016
00017 inline PyObject *stringToPython(const char *input)
00018 {
00019 #if PY_MAJOR_VERSION >= 3
00020 return PyUnicode_FromString(input);
00021 #else
00022 return PyString_FromString(input);
00023 #endif
00024 }
00025
00026 inline std::string stringFromPython(PyObject * input)
00027 {
00028 Py_ssize_t size;
00029 char * data;
00030 #if PY_MAJOR_VERSION >= 3
00031 data = PyUnicode_AsUTF8AndSize(input, &size);
00032 #else
00033 PyString_AsStringAndSize(input, &data, &size);
00034 #endif
00035 return std::string(data, size);
00036 }
00037
00038 inline PyObject *pythonImport(const std::string & name)
00039 {
00040 PyObject *py_name = stringToPython(name);
00041 PyObject *module = PyImport_Import(py_name);
00042 Py_XDECREF(py_name);
00043 return module;
00044 }
00045
00046 inline PyObject *pythonBorrowAttrString(PyObject* o, const char *name)
00047 {
00048 PyObject *r = PyObject_GetAttrString(o, name);
00049 Py_XDECREF(r);
00050 return r;
00051 }
00052
00053 #endif