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

2021/12/31 7:09:37

本文主要是介绍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);


这篇关于Python与CSharp之间内存共享互传信息的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程