|
1 | | -#include <python_compat.h> |
2 | 1 | #include <Python.h> |
3 | 2 |
|
4 | 3 | #include <tf2/buffer_core.h> |
|
7 | 6 | #include <string> |
8 | 7 | #include <vector> |
9 | 8 |
|
| 9 | +/// \brief Converts a C++ string into a Python string. |
| 10 | +/// \note The caller is responsible for decref'ing the returned object. |
| 11 | +/// \note If the return value is NULL then an exception is set. |
| 12 | +/// \return a new PyObject reference, or NULL |
| 13 | +inline PyObject * stringToPython(const std::string & input) |
| 14 | +{ |
| 15 | + return PyUnicode_FromStringAndSize(input.c_str(), input.size()); |
| 16 | +} |
| 17 | + |
| 18 | +/// \brief Converts a C string into a Python string. |
| 19 | +/// \note The caller is responsible for decref'ing the returned object. |
| 20 | +/// \note If the return value is NULL then an exception is set. |
| 21 | +/// \return a new PyObject reference, or NULL |
| 22 | +inline PyObject * stringToPython(const char * input) |
| 23 | +{ |
| 24 | + return PyUnicode_FromString(input); |
| 25 | +} |
| 26 | + |
| 27 | +/// \brief Converts a Python string into a C++ string. |
| 28 | +/// \note The input PyObject is borrowed, and will not be decref'd. |
| 29 | +/// \note It's possible for this function to set an exception. |
| 30 | +/// If the returned string is empty, callers should check if an exception was |
| 31 | +/// set using PyErr_Ocurred(). |
| 32 | +/// \return a new std::string instance |
| 33 | +inline std::string stringFromPython(PyObject * input) |
| 34 | +{ |
| 35 | + Py_ssize_t size; |
| 36 | + const char * data; |
| 37 | + data = PyUnicode_AsUTF8AndSize(input, &size); |
| 38 | + return std::string(data, size); |
| 39 | +} |
| 40 | + |
| 41 | +/// \brief Imports a python module by name. |
| 42 | +/// \note The caller is responsible for decref'ing the returned object. |
| 43 | +/// \note If the return value is NULL then an exception is set. |
| 44 | +/// \return a reference to the imported module. |
| 45 | +inline PyObject * pythonImport(const std::string & name) |
| 46 | +{ |
| 47 | + PyObject * py_name = stringToPython(name); |
| 48 | + if (!py_name) { |
| 49 | + return nullptr; |
| 50 | + } |
| 51 | + PyObject * module = PyImport_Import(py_name); |
| 52 | + Py_XDECREF(py_name); |
| 53 | + return module; |
| 54 | +} |
| 55 | + |
10 | 56 | // Run x (a tf method, catching TF's exceptions and reraising them as Python exceptions) |
11 | 57 | // |
12 | 58 | #define WRAP(x) \ |
|
0 commit comments