系统相关
首页 > 系统相关> > Python与CSharp之间内存共享互传信息

Python与CSharp之间内存共享互传信息

作者:互联网

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);

标签:SHMEMSIZE,file,Python,mmap,互传,str,CSharp,byte,共享内存
来源: https://www.cnblogs.com/supersdar/p/15750022.html