Search code examples
python-3.xctypesmmap

Array of Structs in Python


I cannot use multiprocessing, I need shared memory among entirely separate python processes on Windows using python 3. I've figured out how to do this using mmap, and it works great...when I use simple primitive types. However, I need to pass around more complex information. I've found the ctypes.Structure and it seems to be exactly what I need.

I want to create an array of ctypes.Structure and update an individual element within that array, write it back to memory as well as read an individual element.

import ctypes
import mmap


class Person(ctypes.Structure):
    _fields_ = [
        ('name', ctypes.c_wchar * 10),
        ('age', ctypes.c_int)
    ]

if __name__ == '__main__':
    num_people = 5

    person = Person()

    people = Person * num_people
    mm_file = mmap.mmap(-1, ctypes.sizeof(people), access=mmap.ACCESS_WRITE,     tagname="shmem")

Solution

  • Your people is not an array yet, it's still a class. In order to have your array, you need to initialize the class using from_buffer(), just like you were doing before with c_int:

    PeopleArray = Person * num_people
    mm_file = mmap.mmap(-1, ctypes.sizeof(PeopleArray), ...)
    people = PeopleArray.from_buffer(mm_file)
    
    people[0].name = 'foo'
    people[0].age = 27
    people[1].name = 'bar'
    people[1].age = 42
    ...