[Pyrex] Handling bytes
Brad Schick
schickb at gmail.com
Thu May 8 01:25:33 CEST 2008
The C code I am interfacing with processes fixes size arrays of type
uint8_t. I've seen suggested how to get python strings into and out of C
character arrays, but I don't really like using strings in python code
to hold raw data bytes. Until python 3 arrives with its bytearray stuff,
I often just put byte range ints into traditional sequences (list,
tuple, or array). To handle this in pyrex I could usecode like:
def encrypt(data):
if len(data) != 8:
raise ValueError("data must be 8 bytes long")
cdef uint8_t cin[8]
cdef uint8_t cout[8]
cdef int i
for i from 0 <= i < 8:
cin[i] = data[i]
do_c_encrypt(cin, cout)
result = []
for i from 0 <= i < 8:
result.append(cout[i])
return result
This could be called from python code like:
result = encrypt( [0,1,2,3,4,5,6,7] )
But I'm assuming there is a more efficient approach to converting to and
from python sequences. Maybe I'd be better off using python strings
with PyString_FromStringAndSize and friends? Or perhaps using
PyObject_AsReadBuffer and PyObject_AsWriteBuffer would work, but that
would limit the input object to python array.array('B') or similar
right? Just wondering if there is a preferred approach since I'd assume
this has been hashed over many times.
Thanks,
-Brad
More information about the Pyrex
mailing list