Embedding Python in C++: how to parse a list returned from Python function?

Question:

My code looks something like this:


  PyObject *pArguments, *pArgumentValue;

  pArgumentValue = PyObject_CallObject(pFunction, pArguments);
  Py_DECREF(pArguments);


  if (pArgumentValue != NULL) {
    #?????????????????
  } else {

    PyErr_Print();
  }

I would like to parse the return value of the python method, which returns a list of lists of floating point values. It’s my first time working with python embeds in cpp, so I would appreciate any help and examples!
The result of this parsing can be a list or a vector in cpp, it doesn’t matter that much, as long as this data is usable.

Asked By: robotanical

||

Answers:

Using PySequence was the answer!

  PyObject *pArguments, *pArgumentValue;
  pArguments=nullptr;

  pArgumentValue = PyObject_CallObject(pFunction, pArguments);


  if (pArgumentValue != NULL) {
    cout << "result:" << PySequence_Check(pArgumentValue);
    for (int i = 0; i < PySequence_Size(pArgumentValue); i++) {
      if (PySequence_GetItem(pArgumentValue, i) != NULL) {
        for (int j = 0;
             j < PySequence_Size(PySequence_GetItem(pArgumentValue, i)); j++) {
          cout << "Field: " << i << "Measurement: " << j << " :"
                   << PyLong_AsLong(PySequence_GetItem(
                          PySequence_GetItem(pArgumentValue, i), j));
        }
      }
    }

Answered By: robotanical
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.