Hi,

what is now the canonical way to convert between (python) numpy array and

int *a

or

double *a

?

I looked at the new petsc4py and it uses this method to convert from numpy to C:

cdef inline ndarray iarray_s(object ob, PetscInt* size, PetscScalar** data):
    ob = PyArray_FROM_OTF(ob, NPY_PETSC_SCALAR, NPY_IN_ARRAY)
    cdef ndarray ary = <ndarray> ob
    if size!=NULL: size[0] = <PetscInt>     PyArray_SIZE(ary)
    if data!=NULL: data[0] = <PetscScalar*> PyArray_DATA(ary)
    return ary

The function PyArray_FROM_OTF() is defined in /usr/include/numpy/ndarrayobject.h

And this method to convert from C to numpy:

cdef inline ndarray array_s(PetscInt size, const_PetscScalar* data):
    cdef npy_intp s = <npy_intp> size
    cdef ndarray ary = PyArray_EMPTY(1, &s, NPY_PETSC_SCALAR, 0)
    if data != NULL: memcpy(ary.cdata, data, size*sizeof(PetscScalar))
    return ary


Is this the best way to do things now? When I investigated this half a
year ago, the way to do this was this:

http://wiki.cython.org/WrappingNumpy

however Robert wrote there that now the way is this:

http://wiki.cython.org/tutorials/numpy

unfortunately at the latter page it is only explained how to access
indices of numpy arrays using the buffer interface, but not how to
convert them back and forth to C.

Maybe the canonical methods could be shipped with either numpy or
cython? I can provide a patch, once I learn how to do things properly.

Thanks,
Ondrej
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to