Python之间进行内存共享传递信息
Write.py
import mmap
str = 'hello major!'
byte = str.encode(encoding='UTF-8')
infoSize= len(str)
file_name = 'global_share_memory'
# python写入共享内存
shmem = mmap.mmap(0, infoSize, file_name, mmap.ACCESS_WRITE)
# 共享数据写入共享内存
shmem.write(byte)
# 让其一直运行,因为进程是活的,死了的进程,共享内存也就没了
while True:
pass
Read.py
import mmap
str = 'hello major!'
byte = str.encode()
infoSize= len(str)
file_name = 'global_share_memory'
# python读取共享内存
shmem = mmap.mmap(0, infoSize, file_name, mmap.ACCESS_READ)
# 从共享内存读取共享数据
print(shmem.read(SHMEMSIZE).decode("utf-8"))
shmem.close()
C#读取python的共享内存
long capacity = 6;
var mmf = MemoryMappedFile.OpenExisting("global_share_memory");
MemoryMappedViewAccessor viewAccessor = mmf.CreateViewAccessor(0, capacity);
char[] charsInMMf = new char[6];
byte test = viewAccessor.ReadByte(0);
byte test2 = viewAccessor.ReadByte(1);
byte test3 = viewAccessor.ReadByte(2);
byte test4 = viewAccessor.ReadByte(3);
|