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