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.

6
  • 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? Commented Mar 4, 2016 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". Commented Mar 4, 2016 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? Commented Mar 4, 2016 at 17:13
  • Nothing, it's a useless conversion hence why I don't want to do it. Commented Mar 4, 2016 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? Commented Mar 4, 2016 at 17:24

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.