[capi-sig] How to manipulate C table as python list ?

Marc marcglec at free.fr
Mon Jan 19 18:52:33 CET 2009


Thx to all for your answers, I'm sure I will succeed now :)

Marc.

Le dimanche 18 janvier 2009 à 09:51 +0100, Hrvoje Niksic a écrit :
> Marc <marcglec at free.fr> writes:
> 
> > I would like to use a C program which manipulates table
> > as a python module acting on a list.
> > My C code is the following:
> > int sum(int *tab, int n)
> > {
> >   int i, s = 0;
> >   
> >   for (i=0; i<n; i++)
> >     {
> >       s += tab[i];
> >     }
> >
> >   return s;
> > }
> > Now, I would like to use it as a python module
> > where tab would be a python list.
> > I read some examples in the documentation but
> > the size of the list is always assumed to be known
> > such that one can use PyArg_ParseTuple
> > with a format description for each argument.
> 
> In this case you only use PyArg_ParseTuple to get to the object that
> represents the list.  In fact, since you only need one argument, you
> don't need PyArg_ParseTuple at all, simply declare your function to
> take one argument using the METH_O in the function description, and
> code it like this:
> 
> PyObject *sum(PyObject *ignored, PyObject *lst)
> {
>     int i, s = 0;
>     if (!PyList_Check(lst)) {
>         PyErr_Format(PyExc_TypeError, "sum: expected list, got %s",
>                      lst->ob_type->tp_name);
>         return NULL;
>     }
>     for (i = 0; i < PyList_GET_SIZE(lst); i++) {
>         ... sum the list ...
>     return PyInt_FromLong(s);
> }
> 
> > My question is:
> > which option should I use with PyArg_ParseTuple?
> 
> If your function is declared to take one argument with METH_O, you
> don't need PyArg_ParseTuple at all.  If it's declared to take a
> variable number of arguments, you'd use it like this:
> 
> PyObject *sum(PyObject *ignored, PyObject *args)
> {
>     int i, s = 0;
>     PyObject *lst;
>     if (!PyArg_ParseTuple(args, "O", &lst))
>         return NULL;
>     ...
> }
> 



More information about the capi-sig mailing list