Passing python list from C to python

John Machin sjmachin at lexicon.net
Mon Jul 13 12:35:16 EDT 2009


On Jul 14, 1:47 am, hartley <hartle... at gmail.com> wrote:
> 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 ...

> 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