Getting a Py_buffer from a PyObject or function argument

68 views
Skip to first unread message

Daniele Nicolodi

unread,
Sep 7, 2022, 3:59:26 PM9/7/22
to cython-users
Hello,

is there a way to type the arguments of a function (or some type casting
trickery) that can get me a Py_buffer, equivalent to calling
PyObject_GetBuffer() with the PyBUF_SIMPLE flag or using the "y*" format
string to PyArg_Parse()?

The Cython manual suggests to use memoryview objects to deal with bytes
objects but this restricts the type and number of dimensions and the
data type.

The use case is to write an hashing function with the same interface as
the functions in the hashlib module. For now I resorted at calling the
Py_buffer related functions as I would do in C, but I am wondering
whether there is a more "Cythonic" way.

Thank you.

Best,
Dan

da-woods

unread,
Sep 7, 2022, 4:29:51 PM9/7/22
to cython...@googlegroups.com
I'm not completely sure if you actually want a Py_buffer object or are
looking for any convenient way to access a buffer as raw data. Assuming
the latter, you could go via a regular Python memoryview:

obj_view = memoryview(obj)
obj_view_as_bytes = obj_view.cast('b') # or 'B' if you want it unsigned
cdef signed char[::1] cy_view = obj_view_as_bytes

The cost is essentially one Python function call (memoryview.cast) and
then after that you have it in a Cython char memoryview.
Reply all
Reply to author
Forward
0 new messages