Calling a python function with a list as the input argument from C

Michael Grabietz michael.grabietz at img-online.de
Sun Jul 21 14:45:52 EDT 2002


Hello,

I tried the example given in the Python documentation calling Python 
from C. In this example the input argument of the python function is a 
tuple. See the code below which works fine.


----------------------------------------------------------------
Calling Python function with pArgs as tuple:  That works fine !
--------------------------------------------

     Py_Initialize();                      // Init Python Interpreter
     pName = PyString_FromString(ModuleName);
     pModule = PyImport_Import(pName);       // Import module
     pDict = PyModule_GetDict(pModule);
     pFunc = PyDict_GetItemString(pDict, FunctionName);
     pArgs = PyTuple_New(inp_vec_n);
     for (i = 0; i < inp_vec_n; ++i) {
          pValue = PyFloat_FromDouble( inp_vec[i] );
          PyTuple_SetItem(pArgs, i, pValue);         }

     pValue = PyObject_CallObject(pFunc, pArgs); // Calling Python
----------------------------------------------------------------


----------------------------------------------------------------
Calling Python function with pArgs as a list:  That fails !
---------------------------------------------

Now something I do not understand. I want to call a python function with 
a list as an input argument. I modified the code above to the following.

     Py_Initialize();
     pName = PyString_FromString(ModuleName);
     pModule = PyImport_Import(pName);
     pDict = PyModule_GetDict(pModule);
     pFunc = PyDict_GetItemString(pDict, FunctionName);
//    pArgs = PyTuple_New(inp_vec_n);
     pArgs = PyList_New(inp_vec_n);
     for (i = 0; i < inp_vec_n; ++i) {
          pValue = PyFloat_FromDouble( inp_vec[i] );
//         PyTuple_SetItem(pArgs, i, pValue);
          PyList_SetItem(pArgs, i, pValue);     }

//    pValue = PyObject_CallObject(pFunc, pArgs);
     pValue = PyObject_CallObject(pFunc, pArgs); // Now calling with List
----------------------------------------------------------------


I suppose using 'PyObject_CallObject' is not the right choice. I read 
already in the doc that it expects pArgs as atuple. But what do I have 
to use if I need to pass a list. Further I want to extent it to feed a 
python function with a vector from NumPy as an input argument. Is that 
possible or do I have to stay with tuples ?


Thanks for your efforts and help,

Michael




More information about the Python-list mailing list