Reputation: 303
I want to achieve interprocess communication between Python and C# in order to read values in my C# application which are written by a Python script. In C#, I am using the MemoryMappedFile class:
MemoryMappedFile mmfSimPro = MemoryMappedFile.CreateOrOpen("MyFileMappingObject_SimPro", 20);
MemoryMappedViewAccessor accessorAxesSimPro = mmfSimPro.CreateViewAccessor(0, 20);
for (int i = 0; i < axesSimPro.Length; i++)
axesSimPro[i] = accessorAxesSimPro.ReadSingle(sizeof(float) * i);
It reads the values successfully, but after that it sets the values in the memory mapped file to zero. So if I read the memory mapped file again (and it hasn't been overwritten by the Python script yet), I will read only zeros. How can I prevent that?
My python script looks as follows:
def WriteAxes():
shmem = mmap.mmap(0,256, "MyFileMappingObject_SimPro",mmap.ACCESS_WRITE)
struct.pack_into('f',shmem,0,_ctrl.Joints[1].CurrentValue)
struct.pack_into('f',shmem,4,_ctrl.Joints[0].CurrentValue)
struct.pack_into('f',shmem,8,_ctrl.Joints[2].CurrentValue)
struct.pack_into('f',shmem,12,_ctrl.Joints[3].CurrentValue)
struct.pack_into('f',shmem,16,_ctrl.Joints[4].CurrentValue-90)
shmem.close()
Upvotes: 1
Views: 772
Reputation: 3724
Since you are using .CreateOrOpen
you are using a Non-Pesisted MemoryMappedFile ( see https://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx) which means the GC is free to GC the contents
I am making some assumptions about the rest of your code but it looks like you CreateOrOpen and read in a single method, thus the GC is free to dispose the contents as soon as you have finished reading, basically this is some memory your C# app owns and it will be GCed as normal.
You would need either to .CreateOrOpen
in some wider context of A (ie it is opened (and kept referenced) at app startup or in whatever appropriate 'session' object) or move to .CreateFromFile
to view it as persistent (perhaps with some manual zeroing out at the begining if that is needed / appropriate).
TLDR; mmfSimPro
should probably be held at app / class level in a field not in a local variable so it has a live GC handle for the app / class lifetime and NOT just for the length of the read method.
Upvotes: 1