0

I have knowledge of C and Python, but I am new to Cython.

I have a view on a (contiguous) array of double. I want to iterate over the items of the view through a pointer and an index, as we would do in C. However, I cannot express that with Cython:

from cpython cimport array
import array

arr = array.array("d", (1,2,3,4))

cdef double[::1] view = arr[::1]
cdef unsigned l = len(view)
cdef double *ptr = view.as_doubles

# Iterate over the view items
cdef double acc = 0.0
cdef unsigned i
for i in range(l):
    acc += ptr[i]

The code above is rejected with an error:

a.pyx:8:5: Storing unsafe C derivative of temporary Python reference

How can I fix that?

Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125

2 Answers2

1
acc += view[i]

There's really no point in involving pointers here - indexing a typed memoryviews should have comparable performance. (You may want to disable boundschecking and wraparound with the appropriate Cython compiler directives if you're sure that you don't need them while indexing)

DavidW
  • 29,336
  • 6
  • 55
  • 86
  • Thanks for the reply, David. But admitting I really need a pointer to the underlying buffer (say, to pass that to an external C function `f(const double*, size_t)`). How could I do that? – Sylvain Leroux Apr 09 '23 at 21:17
  • https://stackoverflow.com/a/14585530/4657412, https://stackoverflow.com/a/54832269/4657412 – DavidW Apr 09 '23 at 21:25
  • Indeed! I found that about at the same time as you pointed it to me! https://stackoverflow.com/a/75972960/2363712 – Sylvain Leroux Apr 09 '23 at 21:27
0

I mixed up the syntax for (untyped) arrays with ....as_doubles and the syntax for (typed) memory views.

The correct code should have been:

cdef double *ptr = &view[0]
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125