Python Window下共享内存读写

导入win32的包

import win32event as w32e 
import mmapfile as mmf 

创建共享内存

fileMemory = mmf.mmapfile(None, 'ai_and_imghandle_shareMem', 1024*1024*2)

创建事件

# 创建读事件 hReadEvent 和 写事件 hWriteEvent
hReadEvent, hWriteEvent = None, None
#创建时判断系统是否已经有该事件
try:
    hReadEvent = w32e.OpenEvent(w32e.EVENT_ALL_ACCESS , 0, "Global\\readEventHandle")
    hWriteEvent = w32e.OpenEvent(w32e.EVENT_ALL_ACCESS , 0, "Global\\writeEventHandle")
except Exception as e:
    print('Excep: ', e)
    hReadEvent = w32e.CreateEvent(None, 0, 0, "Global\\readEventHandle")
    hWriteEvent = w32e.CreateEvent(None, 0, 0, "Global\\writeEventHandle")

数据写入内存

fileMemory.seek(0) # 游标移至0
fileMemory.write(img_path.encode(encoding='utf-8')) # 对数据进行编码
fileMemory.write('\0\0\0'.encode(encoding='utf-8')) # 输入\0终止符
# 触发Write事件,通知其他进程可读取共享内存的数据
w32e.SetEvent(self.hWriteEvent)

从内存读取数据

# 等待Read事件的触发
w32e.WaitForSingleObject(self.hReadEvent, -1)
# 触发后读取新内存
fileMemory.seek(0)
buf = fileMemory.read(1024*1024*2)
# 解析数据, 设置erros忽略部分错误
result = buf.decode(encoding = "utf-8", errors='ignore').strip("\0")
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试 返回首页