1

I am trying to call a Python method from C++ code and the method I am calling takes a file name as an argument returns a list.

My sample code currently converts PyObject* result of the method call to a double but I want to convert this to a list.

#include "include.h"

int main(int argc, char* argv[])
{
   double answer = 0;
   PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *result;

   Py_Initialize();

   PyRun_SimpleString("import sys");
   modname = PyUnicode_FromString("module");
   mod = PyImport_Import(modname);
   if (!mod)
   {
       PyErr_Print();
       exit(1);
   }

   mdict = PyModule_GetDict(mod);
   func = PyDict_GetItemString(mdict, "func"); 
   if (!func)
   {
       printf("function does not exist\n");
   }

   stringarg = PyUnicode_FromString("test.txt");
   args = PyTuple_New(1);
   PyTuple_SetItem(args, 0, stringarg);

   result = PyObject_CallObject(func, args);
   if (result)
   {
       answer = PyFloat_AsDouble(result);
       Py_XDECREF(result);
   }
   Py_XDECREF(stringarg);
   Py_XDECREF(args);

   Py_XDECREF(mod);

   Py_XDECREF(modname);

   Py_Finalize();

   return 0;
   }

How would I go about doing this? I have seen examples of wrapper classes to create list objects passed as an argument but I haven't seen examples to convert a returned value to a list.

Paul
  • 94
  • 1
  • 9
  • What do you mean convert to a list? Right now it looks like you're assuming it returns a `float`. You want to just get a list of that one float? – Barry Mar 04 '16 at 16:58
  • As I said "My sample code currently converts PyObject* result to a double but I want to convert this to a list". – Paul Mar 04 '16 at 17:06
  • When I asked to clarify your question, I didn't mean for you to literally quote the part that I was asking clarification about. What does converting a double to a list mean to you? – Barry Mar 04 '16 at 17:13
  • Nothing, it's a useless conversion hence why I don't want to do it. – Paul Mar 04 '16 at 17:16
  • So what is your question?? What is the problem that you are trying to solve but can't? What do you want to do with `result`? – Barry Mar 04 '16 at 17:24
  • I want to convert rslt to a list. Your comment was very helpful and should allow me to do what I want. Thank you. – Paul Mar 04 '16 at 17:27

1 Answers1

3

You're looking for the List Objects section of the API:

result = PyObject_CallObject(func, args);
if (PyList_Check(result)) {
    // okay, it's a list
    for (Py_ssize_t i = 0; i < PyList_Size(result); ++i) {
        PyObject* next = PyList_GetItem(result, i);
        // do something with next
    }
}
Barry
  • 286,269
  • 29
  • 621
  • 977