Buffers (note that you'd get the same behaviour using
np.ndarray[datum_df]) don't support every character format or dtype
yet, unfortunately. It seems 'c' and 's' are one of them, so you're
stuck with 'b', 'B' or 'i1' apparently, which I agree is frustrating.
Note that Cython's 'char' converts to an integer in any case, so you'd
have to cast it in Cython space anyway, using <bytes> c. You could
decide to actually use char[1], which will convert to bytes, but that
breaks in the compiler. It's really something that should be fixed,
probably before the next release.
Yes, you use char in your struct, as you're doing now, and you can use
'i1' or 'B' or whatever, and cast like you just showed. In example
print <bytes> myslice[myidx].f
Is that what you're asking for?
> Can I cast a pointer to the ndarray data as a memoryview and just have it
> ignore the numpy dtype?
> --Bill
>
Yes, you can. You can use numpy.PyArray_DATA() to get the data
pointer, and use <datum_df[:shape0, :shape1, ..., :shapeN]> to convert
the pointer to a cython.array (from which you can obtain a memoryview
slice).
Basically casting memoryview slices doesn't work, what would it do?
Would it create a copy and convert all elements to a new type? So the
casting syntax is used to obtain views on C data that you have, i.e. a
pointer or a C array.
So what you want is this (I agree it's somewhat convoluted):
cimport numpy as np
cdef datum_df *p = <datum_df *> np.PyArray_DATA(my_numpy_ndarray)
cdef Py_ssize_t shape0 = my_numpy_ndarray.shape[0]
cdef datum_df[:] myslice = <datum_df[:shape0]> p
The idea in the cast to memoryview slice is that you provide shape
information that tells Cython "my pointer points memory that can be
viewed like this and this is how big it is".
Hope that helps,
Mark
Something slightly more Pythonic, perhaps, than what Mark suggested is
m_tx = arr.view(np.dtype([('d','<f4'),('f','i1')]))
That is, even if Cython memoryviews can't be casted, you can use the
view method of NumPy to do the cast.
Dag Sverre
Something slightly more Pythonic, perhaps, than what Mark suggested is
m_tx = arr.view(np.dtype([('d','<f4'),('f','i1')]))
That is, even if Cython memoryviews can't be casted, you can use the
view method of NumPy to do the cast.Dag Sverre
You should be able to use strings with the latest Cython now:
https://github.com/cython/cython/commit/e52e87714ab15f5993362d68d1449231819fb016
This means you will have to declare 'char f' as 'char f[1]'.