[Python-Dev] ctypes, memory mapped files and context manager

Hans-Peter Jansen hpj at urpla.net
Thu Jan 5 19:03:30 EST 2017


On Freitag, 6. Januar 2017 00:28:37 Hans-Peter Jansen wrote:
> Hi Eryk,
> 
> This is exactly, what I was after:
> 
> @contextmanager
> def cstructmap(cstruct, mm, offset = 0):
>     # resize the mmap (and backing file), if structure exceeds mmap size
>     # mmap size must be aligned to mmap.PAGESIZE
>     cssize = ctypes.sizeof(cstruct)
>     if offset + cssize > mm.size():
>         newsize = align(offset + cssize, mmap.PAGESIZE)
>         mm.resize(newsize)
>     cmap = cstruct.from_buffer(mm, offset)
>     try:
>         yield cmap
>     finally:
>         for mv in cmap._objects.values():
            if isinstance(mv, memoryview):
                mv.release()

It happens, that _objects contain other objects as well...

Cheers,
Pete


More information about the Python-Dev mailing list