ctypes, memory mapped files and context manager

Peter Otten __peter__ at web.de
Fri Dec 30 05:08:19 EST 2016


eryk sun wrote:

> On Thu, Dec 29, 2016 at 12:18 PM, Hans-Peter Jansen <hpj at urpla.net> wrote:
>>> >>> import weakref, ctypes
>>> >>> T = ctypes.c_ubyte * 3
>>> >>> t = T()
>>> >>> bytes(t) == b"\0" * 3
>>>
>>> True
>>>
>>> >>> bytes(weakref.proxy(t)) == b"\0" * 3
>>>
>>> Traceback (most recent call last):
>>>   File "<stdin>", line 1, in <module>
>>> AttributeError: 'c_ubyte_Array_3' object has no attribute '__bytes__'
>>>
>>> That looks like a leaky abstraction. While I found a workaround
>>>
>>> >>> bytes(weakref.proxy(t)[:]) == b"\0" * 3
>>>
>>> True
>>
>> I found a couple of other rough corners already, when working with the
>> ctypes module. Obviously, this module is lacking some love.
> 
> That's not the fault of ctypes. 

By adding a Structure.close() method that would release the underlying 
memoryview reference and make all further attribute access fail ctypes could 
support Hans-Peter's use case quite easily. In that sense I think it is the 
"fault" or rather a limitation of ctypes. I'm not sure though whether ctypes 
is the right tool here in the first place. 

Anyway, as long as he gets enough advantages from his current approach a few 
odd del statements might be OK.



More information about the Python-list mailing list