Passing python list from C to python

hartley hartley79 at gmail.com
Tue Jul 14 05:22:24 EDT 2009


> > I'm very new at wrapping Python/C, and I have run into some problems.
>
> > I have one python module that provides me with a list (provideBuffer
> > in provideBuff.py):
>
> >  Py_Initialize();
> >         pName = PyString_FromString("provideBuff");
> >         pModule = PyImport_Import(pName);
>
> >         pFunc = PyObject_GetAttrString(pModule,"provideBuffer");
>
> >         pValue = PyObject_CallObject(pFunc,NULL);
>
> > pValue is now a PyList - i've even verified this with:
>
> > int a = PyList_Check(pValue);
> >         printf("%d\n", a);
>
> > However, I want to send this PyList to another python module,
>
> Please explain "send" ... do you mean the C equivalent of the Python
> statement C_embedding.buff = the_pylist ?
>
> BTW C-embedding would trigger a syntax error in Python source; best to
> avoid ...


I'm sorry I'm not using the proper terms when trying to describe this
- i've never really learnt those terms, I guess i should do that one
day.


Imagine that the python function C-embedding.buff looks like this:

def buff(a):
    if isinstance(a,list):
        print "success"

I want to send, pass, call, whatever a list argument from the C code
onto this function. As simple as this - how can you call a function in
python from C, and providing a python list as an argument?

As I wrote earlier - I already have a PyList, called pValue. But I
have not been able to use this as an argument for C-embedding.buff
using the code I described last time.


> > but I
> > don't know how to do this. Initially I though I could just do like
> > above, only swapping NULL with pValue, but that is not working.
>
> > pName2 = PyString_FromString("C-embedding");
> > pModule2 = PyImport_Import(pName2);
> > pFunc2 = PyObject_GetAttrString(pModule2,"buff");
>
> Get?? Do you want Set? Is buff a Python function? Or is it the
> destination of the "sending"? Any good reason for not checking the
> return value for an error? [Rhetorical question; answer == "No"]
>
> > pValue2 = PyObject_CallObject(pFunc2,pValue);
>
> CallObject?? You used this before because you had a function and
> wanted to call it because it returned you a value .... now you want to
> do one of (in Python terms)
>
> value = amodule.anattr
> value = getattr(amodule, "anattr")
>
> or
>
> amodule.anattr = value
> setattr(amodule, "anattr", value)
>
> > pValue2 is now False!
>
> False?? Do you mean the C NULL?
>
> > So i guess i cannot pass pValue as an argument
> > to PyObject_CallObject when i want to pass an python list as an
> > argument. But how must a go about to make this work?
>
> It's mainly just a matter of (1) knowing what you want to do (2)
> picking the API that does what you want (3) checking the returned
> value for error after every call.
>
> HTH,
> John




More information about the Python-list mailing list