how to read a list from python in C?

2006-05-19 Thread Lialie KingMax

Hi, all

I am writing a C extension with .Net.
Now I have a list of points, like [(0.0, 0.0), (2.0, 3.0), (random x,
random y)].
Is there a better way to translate it to an array than doing it one by one?

Thanks


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to read a list from python in C?

2006-05-19 Thread skip

Lialie I am writing a C extension with .Net.  Now I have a list of
Lialie points, like [(0.0, 0.0), (2.0, 3.0), (random x, random y)].
Lialie Is there a better way to translate it to an array than doing it
Lialie one by one?

Are you passing a list as an argument to one of the functions in your C
extension module?  If so, yup, you get the list argument and march through
it element-by-element, then march through those tuples.  For more detail on
argument handling in C, read here:

http://www.python.org/doc/api/arg-parsing.html

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to read a list from python in C?

2006-05-19 Thread skip

lialie The list has a random length.
lialie Do you mean to do it in this way?
lialie use PyTuple_Size(args), in a loop
lialie use PyTuple_GetItem(args, i) 
lialie or
lialie use PyArg_VaParse?

Sketch (that means off-the-top-of-my-head, untested,  99.9% guaranteed
incorrect in some fashion):

static PyObject *
my_list_method(PyObject *self, PyObject *args) {
PyListObject *list = NULL;
PyTupleObject *point = NULL;
int list_len;
double *points = NULL;
double x, y;

if (PyArg_ParseTuple(args, O!, PyList_Type, list) == NULL)
return NULL;

list_len = PyList_GetSize(list);
points = PyMem_Alloc(list_len * 2 * sizeof(double));
if (points == NULL)
goto fail;

for (i = 0; i  list_len; i++) {
point = PyList_GetItem(list, i)
if (point == NULL || !PyTuple_Check(point))
goto fail;
if (Py_ArgParseTuple(point, (dd), x, y) == NULL)
goto fail;
Py_DECREF(point);
points[i*2] = x;
points[i*2+1] = y;

/* do your thing with your list of floats here */
...

PyMem_Free(points);
Py_DECREF(list);

Py_INCREF(None);   /* or whatever makes sense */
return None;

fail:
Py_XDECREF(list);
Py_XDECREF(point);
if (points != NULL)
PyMem_Free(points);
return NULL;
}


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to read a list from python in C?

2006-05-19 Thread Lialie


Thanks for your reply.
yes, I pass a list as an argument to the function in C.
The list has a random length.
Do you mean to do it in this way?
use PyTuple_Size(args), in a loop
use PyTuple_GetItem(args, i) 
or

use PyArg_VaParse?

Best Regards


-- 
http://mail.python.org/mailman/listinfo/python-list