python_compat.h
Go to the documentation of this file.
1 #ifndef TF2_PY_PYTHON_COMPAT_H
2 #define TF2_PY_PYTHON_COMPAT_H
3 
4 #include <Python.h>
5 
6 #include <string>
7 
8 inline PyObject *stringToPython(const std::string &input)
9 {
10 #if PY_MAJOR_VERSION >= 3
11  return PyUnicode_FromStringAndSize(input.c_str(), input.size());
12 #else
13  return PyString_FromStringAndSize(input.c_str(), input.size());
14 #endif
15 }
16 
17 inline PyObject *stringToPython(const char *input)
18 {
19 #if PY_MAJOR_VERSION >= 3
20  return PyUnicode_FromString(input);
21 #else
22  return PyString_FromString(input);
23 #endif
24 }
25 
26 inline std::string stringFromPython(PyObject * input)
27 {
28  Py_ssize_t size;
29 #if PY_MAJOR_VERSION >= 3
30  const char * data;
31  data = PyUnicode_AsUTF8AndSize(input, &size);
32 #else
33  char * data;
34  PyString_AsStringAndSize(input, &data, &size);
35 #endif
36  return std::string(data, size);
37 }
38 
39 inline PyObject *pythonImport(const std::string & name)
40 {
41  PyObject *py_name = stringToPython(name);
42  PyObject *module = PyImport_Import(py_name);
43  Py_XDECREF(py_name);
44  return module;
45 }
46 
47 inline PyObject *pythonBorrowAttrString(PyObject* o, const char *name)
48 {
49  PyObject *r = PyObject_GetAttrString(o, name);
50  Py_XDECREF(r);
51  return r;
52 }
53 
54 #endif
PyObject * stringToPython(const std::string &input)
Definition: python_compat.h:8
PyObject * pythonBorrowAttrString(PyObject *o, const char *name)
Definition: python_compat.h:47
PyObject * pythonImport(const std::string &name)
Definition: python_compat.h:39
#define PyUnicode_FromString
std::string stringFromPython(PyObject *input)
Definition: python_compat.h:26


tf2_py
Author(s):
autogenerated on Mon Feb 28 2022 22:27:24