Handling bytes

Brad Schick <[email protected]>
Newsgroups gmane.comp.python.pyrex
Message-ID <[email protected]>
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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.