1

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")
asked May 3, 2018 at 21:17

1 Answer 1

4

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
...
answered May 3, 2018 at 21:39
Sign up to request clarification or add additional context in comments.

2 Comments

interestingly...it doesn't want bytes, it wants a unicode string. So this works if you remove the b from in front of those string literals.
I can't upvote you due to lack of rep but answer was accepted.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.