ctypes And The WACAH Principle

eryk sun eryksun at gmail.com
Wed Aug 10 23:23:00 EDT 2016


On Wed, Aug 10, 2016 at 10:26 PM, Lawrence D’Oliveiro
<lawrencedo99 at gmail.com> wrote:
> But it has to copy the bytes into an array.array object, then decode that. Is there a way it
> could access the bytes memory directly?

ctypes cast, string_at, wstring_at, memmove, and memset are
implemented as FFI calls. Since ctypes FFI calls convert bytes
arguments to the base address of the buffer, you can cast() bytes to
c_void_p to get the address. For example:

    >>> data = b'abc'
    >>> addr = ctypes.cast(data, ctypes.c_void_p).value
    >>> ctypes.string_at(addr, 3)
    'abc'

For bytearray, use the buffer interface to create a ctypes array. The
array is not a copy. For example:

    >>> data = bytearray(b'abc')
    >>> a = (ctypes.c_char * len(data)).from_buffer(data)
    >>> addr = ctypes.addressof(a)
    >>> ctypes.string_at(addr, 3)
    'abc'



More information about the Python-list mailing list