Direct use of bytearray buffers with ctypes ?

Pakal chambon.pascal at
Sun Jan 10 10:42:23 CET 2010

Oki, it seems I've found.
To directly use a bytearray buffer from ctypes, you must first create
a compatible ctypes type (I.E, a char array of same size), and only
then instanciate this new type with newtype.from_buffer

The little danger is : you must NOT change the size of bytearray as
long as the ctypes array targets its inner buffer, else of cousre
memory reallocations occurs, and your ctypes array points to invalid
memory (awaiting a pretty segfault). But modifying chars or characters
ranges from the buffer, as well via the bytearray object than via the
ctypes array, is fine.

I don't think problems can occur if both sides are accessed
simultaneously, even though ctypes operations may release the GIL
while they execute... the only race condition is the access of a
memory segment, isn't it ? No crash shall occur with this...

IDLE 2.6.4
>>> import ctypes
>>> a = bytearray(3)
>>> mytype = ctypes.c_char * 3
>>> h = mytype.from_buffer(a)
>>> h
<__main__.c_char_Array_3 object at 0x02B06350>
>>> h[:] = "abc"
>>> a
>>> h[0] = "k"
>>> a

More information about the Python-list mailing list