passing list from C to Python

Mike Müller mmueller at dgfz.de
Tue Dec 12 07:21:52 EST 2000


How can I pass a list of values from C to Python an get the list back after
Python did some data manipulation on it?

I am not very familiar with C and use it only to get a call to a DLL from a
FORTRAN program . The functionality of the DLL is in Python. I am able to
call a function in python from the DLL  and get a return value like:

def test_int4(x,y):
    return x+y

I can do the same with doubles, so far everything is ok. All the win32/VC++
specific stuff seems to work.

Now my problem:
I have a lot of values which should be passed by reference to Python, i.e. I
want to change the values of all the arguments.

My approach would be to put them in a PyListObject and pass it to Python
(PyObject_CallMethod does nit work though). As return value I would get a
new PyListObject back which I could “unpack” to the new values of the FORTAN
function arguments.

Python:

def func(list):
      newList = []
      for x in list:
            y = do stuff(x)
           newList.append(y)
     return newList

VC++ 6.0

extern "C" {  __declspec(dllexport) int  C_func_called_in DLL(double *arg1,
double *arg2)
// this works
{ Py_Initialize();
        if(PyErr_Occurred()) {
            PyErr_Print();
            return FALSE;
module_object = PyImport_ImportModule("pythonModul");
        if(PyErr_Occurred()) {
            PyErr_Print();
            return FALSE;
        }
        if(!module_object) return FALSE;

PyListObject *list = Py_BuildValue("[ff]”, *arg1, *arg2);
PyErr_Clear();

// the following does not work, need something that calls python function
with list
    PyListObject *newList = PyObject_CallMethod(module_object,

"pythonModul", list);

PyObject* dataFromPy1 = PyList_GetItem(newList, 0);
PyObject* dataFromPy2 = PyList_GetItem(newList, 1);
*arg1 = PyFloat_asDouble(dataFromPy1);
*arg1 = PyFloat_asDouble(dataFromPy2);

return 0; //everything is ok
}


This might be faulty code, it just shows my intention what I WOULD like to
do.

If there is any other simple way to do it, please let me know.
Hope things are not too confusing.
Thanks.

Mike






More information about the Python-list mailing list