C#和python端通信之使用共享内存

2024-06-21 06:04

本文主要是介绍C#和python端通信之使用共享内存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、前言

    本篇主要实验通过使用共享内存实现C#端代码和python端代码之间的通信,主要目的是相较于直接传输较大的数据(例如图像数据),该方式更节省时间。

二、代码

C#端:

    创建了一个大小为1的共享内存,名为flag1,存放一个byte变量,初始写入0

    创建了一个大小为1的共享内存,名为done,存放一个byte变量,初始写入1

    创建了一个大小为1024 * 16的共享内存,名为result,存放一个string变量,初始写入""

     之后读取图像,并创建和写入至一个大小为960*640*4的共享内存,名为cam1,存放一个byte[]变量 , 然后 flag1 写入1,循环读取done内存,若为1,则将result 内存读取出为string 并显示textBox1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using System.Drawing.Imaging;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;namespace testShareMemory
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void test_0(){// 读取图片string imagePath = "E:/cshape_test/testShareMemory/001.png";Bitmap bitmap = new Bitmap(imagePath);// 确保图片大小为960x640if (bitmap.Width != 960 || bitmap.Height != 640){Console.WriteLine("图片尺寸不符合要求,必须为960x640");return;}MemoryMappedFile mmfCam1 = MemoryMappedFile.CreateOrOpen("cam1", bitmap.Width * bitmap.Height * 4);MemoryMappedViewAccessor accessor = mmfCam1.CreateViewAccessor();BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);byte[] buffer = new byte[bitmapData.Stride * bitmapData.Height];Marshal.Copy(bitmapData.Scan0, buffer, 0, buffer.Length);accessor.WriteArray(0, buffer, 0, buffer.Length);bitmap.UnlockBits(bitmapData);// 创建共享内存 flag , 并写入1var flagMMF = MemoryMappedFile.CreateOrOpen("flag1", 1);var flagAccessor = flagMMF.CreateViewAccessor();byte flagToWrite = 1;flagAccessor.Write(0, flagToWrite);//创建共享内存 done , 并写入0var doneMMF = MemoryMappedFile.CreateOrOpen("done", 1);var doneAccessor = doneMMF.CreateViewAccessor();byte doneToWrite = 0;doneAccessor.Write(0, doneToWrite);//创建共享内存 result , 并写入""int res_lens = 1024 * 32;MemoryMappedFile mmfResult = MemoryMappedFile.CreateOrOpen("result", res_lens);MemoryMappedViewAccessor resAccessor = mmfResult.CreateViewAccessor();byte[] strBytes = Encoding.UTF8.GetBytes("");//resAccessor.Write(0, strBytes.Length); // 首先写入字符串长度resAccessor.WriteArray(0, strBytes, 0, strBytes.Length); // 然后写入字符串字节内容// 循环间隔1秒,读取共享内存bool done = false;int search_times = 0;while (!done){byte doneValue = doneAccessor.ReadByte(0);byte flagValue = flagAccessor.ReadByte(0);if (doneValue == 1 && flagValue == 2){// 读取共享内存"result"string result;// 读取字符串长度(前4个字节)int length = resAccessor.ReadInt32(0);// 创建字节数组来存储字符串数据byte[] buffer_str = new byte[length];// 从共享内存读取字符串数据resAccessor.ReadArray(4, buffer_str, 0, length);// 将字节数组转换为字符串string resultString = Encoding.UTF8.GetString(buffer_str);textBox1.Text = "查询到的结果为: " + resultString;done = true; // 设置标志,退出循环}else{// 等待一段时间再继续轮询System.Threading.Thread.Sleep(1000); // 等待1秒search_times++;if (search_times > 100){//Console.WriteLine("查询超时!"   );textBox1.Text = "查询超时!";break;}}}}private void Form1_Load(object sender, EventArgs e){test_0();}}
}

python端:

    循环读取flag1共享内存,若为1,则读取cam1数据,还原为图像数据,将2写入flag1,并将json字符串data写入result内存区,将1写入done,显示图像数据

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 27 17:10:01 2024@author: WIN10
"""import os , cv2
import numpy as npfrom multiprocessing import shared_memory
import time
import structimport json# 创建/打开共享内存
def create_or_open_shared_memory(name, size):try:shm = shared_memory.SharedMemory(create=False, name=name)except FileNotFoundError:shm = shared_memory.SharedMemory(create=True, name=name, size=size)return shmdef main():flag_name = "flag1"cam1_name = "cam1"done_name = "done"# 图像大小width, height, channels = 960, 640, 4image_size = width * height * channelsflag_shm = create_or_open_shared_memory(flag_name, size=1)  # 1个字节,用 uint8flag_array = np.ndarray((1,), dtype= np.uint8  , buffer=flag_shm.buf)done_shm = create_or_open_shared_memory(done_name, size=1)done_array = np.ndarray((1,), dtype=np.uint8, buffer=done_shm.buf)# 初始化 cam1 共享内存cam1_shm = create_or_open_shared_memory(cam1_name, size=image_size)cam1_array = np.ndarray((height, width, channels), dtype=np.uint8, buffer=cam1_shm.buf)res_shm =  create_or_open_shared_memory("result", size= 1024*16 )while True:if flag_array[0] == 1:# 读取图像数据image_rgba = np.copy(cam1_array)img  = cv2.cvtColor(image_rgba, cv2.COLOR_RGBA2RGB)  #C#端的bitmap传过来的是4通道的,应该转为3通道# 将 2 写入 flagflag_array[0] = 2#写入 jason字符串到 resultdata = {"name": "Mario","age": 28,}json_str = json.dumps(data)json_bytes = json_str.encode('utf-8')res_shm.buf[:4] = struct.pack('i', len(json_bytes))res_shm.buf[4:4 + len(json_bytes)] = json_bytesdone_array[0] = 1  #done 区域写入1# 显示读取到的图像cv2.imshow('Shared Memory Image', img )cv2.waitKey(0)break# 每隔100毫秒检测一次time.sleep(0.1)# 关闭共享内存cam1_shm.close()flag_shm.close()res_shm.close()done_shm.close()if __name__=="__main__":main()

三、运行结果

   先运行C# ,再运行python端

python端结果,显示接受到的图像

C#端结果,显示收到python端写入的json字符串

这篇关于C#和python端通信之使用共享内存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1080391

相关文章

使用Python创建一个功能完整的Windows风格计算器程序

《使用Python创建一个功能完整的Windows风格计算器程序》:本文主要介绍如何使用Python和Tkinter创建一个功能完整的Windows风格计算器程序,包括基本运算、高级科学计算(如三... 目录python实现Windows系统计算器程序(含高级功能)1. 使用Tkinter实现基础计算器2.

在.NET平台使用C#为PDF添加各种类型的表单域的方法

《在.NET平台使用C#为PDF添加各种类型的表单域的方法》在日常办公系统开发中,涉及PDF处理相关的开发时,生成可填写的PDF表单是一种常见需求,与静态PDF不同,带有**表单域的文档支持用户直接在... 目录引言使用 PdfTextBoxField 添加文本输入域使用 PdfComboBoxField

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例