extending with C
Jesper Olsen
jolsen at mailme.dk
Fri Jan 11 06:48:31 EST 2002
Thanks for all the replies - they were useful.
I am not sure if the "dirty" tupel example would work directly;
the PyTuple_GET_ITEM() function
> floatlist[loop] = PyTuple_GET_ITEM(tuple, loop);
returns a PyObject, which I think is not a float, but rather a pointer to
a structure containing a reference count and in this case a pointer to
a float?
So it would be necessary to explicitly extract the float from the float object:
float f=PyFloat_AsFloat(PyObject *pyfloat)
Anyway, in the end I chose the array solution, which I think is quite
elegant:
static PyObject * get_array_of_float
(
PyObject *self,
PyObject *args
)
{
float* farray=get_float_array();
return Py_BuildValue("s#", (char*) farray, SIZE*sizeof(float));
} /* get_array_of_float */
static PyObject * pass_float_array
(
PyObject *self,
PyObject *args
)
{
char* fbuf;
float* farray;
int i;
if(!PyArg_ParseTuple(args,"si", &fbuf, &frame_counter)) return NULL;
farray=(float *) fbuf;
for (i=0; i<SIZE; i++)
printf("%f ", farray[i]);
Py_INCREF(Py_None);
return Py_None;
} /* pass_float_array */
>From python these functions can be called as:
str=get_array_of_float()
a=array("f")
a.fromstring(str)
and
pass_float_array(a.tostring())
I am not super enthusiastic about the python array type
- I have not cheked the implementation, but given the operations
on it, it can not map well to c-arrays.
Cheers
Jesper
Pete Shinners <pete at shinners.org> wrote in message news:<3C3C6E95.9020103 at shinners.org>...
> Jesper Olsen wrote:
>
> > I need to write a python extension in C, and the method interface should
> > be able to handle "arrays of float".
> >
> > In the python code, the array could be represented as a tupel, a list or
> > an array it is not really important.
> >
> > The extension needs to be able to receive such arrays, and to return them
> > to python.
>
>
> here's a quick dirty sample, reading a set of floats from inside a tuple...
>
>
> PyObject* do_floats(PyObject* self, PyObject* args)
> {
> PyObject* tuple;
> float* floatlist;
> int size, loop;
>
> if(!PyArg_ParseTuple("O", &tuple))
> return NULL;
> if(!PyTuple_Check(tuple))
> {
> PyErr_SetString(PyExc_TypeError, "need tuple");
> return NULL;
> }
>
> size = PyTuple_Size(tuple);
> floatlist = PyMem_New(float, size);
> if(!floatlist)
> return NULL;
> for(loop = 0; loop<size; ++loop)
> floatlist[loop] = PyTuple_GET_ITEM(tuple, loop);
>
> /* DO SOMETHING WITH THE FLOATLIST HERE */
>
> PyMem_Del(floatlist);
> Py_INCREF(Py_None);
> return Py_None;
> }
>
>
> of course, my email composer probably parses this better than a real c
> compiler, so you might find some typos in there. :]
More information about the Python-list
mailing list