Direct use of bytearray buffers with ctypes ?
chambon.pascal at gmail.com
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...
>>> import ctypes
>>> a = bytearray(3)
>>> mytype = ctypes.c_char * 3
>>> h = mytype.from_buffer(a)
<__main__.c_char_Array_3 object at 0x02B06350>
>>> h[:] = "abc"
>>> h = "k"
More information about the Python-list