Python與CSharp之間記憶體共享互傳資訊
阿新 • • 發佈:2021-12-30
C#寫入字串到共享記憶體
try { long t = 1 << 10 << 10; var mmf = MemoryMappedFile.CreateOrOpen("test1", t, MemoryMappedFileAccess.ReadWrite); var viewAccessor = mmf.CreateViewAccessor(0, t); string s = "123"; viewAccessor.Write(0, s.Length); ; viewAccessor.WriteArray<byte>(0, System.Text.Encoding.Default.GetBytes(s), 0, s.Length); // MessageBox.Show("write ok"); } catch (System.Exception s) { MessageBox.Show(s.Message); }
Python從共享記憶體中讀取
import mmap
str = '123'
byte = str.encode()
SHMEMSIZE = len(str)
file_name = 'test1'
print(SHMEMSIZE)
# python讀取共享記憶體
shmem = mmap.mmap(0, SHMEMSIZE, file_name, mmap.ACCESS_READ)
print(shmem.read(SHMEMSIZE).decode('ASCII'))
shmem.close()
二
Python寫入字串到共享記憶體
import mmap str = '123456' byte = str.encode(encoding='UTF-8') SHMEMSIZE = len(str) file_name = 'global_share_memory' print(file_name) # python寫入共享記憶體 shmem = mmap.mmap(0, SHMEMSIZE, file_name, mmap.ACCESS_WRITE) shmem.write(byte) while True: pass
C#從共享記憶體中讀取
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);