C#不通过byte[],直接对内存映射文件复制内存

背景

多个进程直接需要传递大量图片,所以对性能要求较高。支付复制内存显然比转成byte[]再复制优越。

命名空间

using System;

using System.Diagnostics;

using System.Runtime.InteropServices;

代码

public CMainTestForm()

{

InitializeComponent();

WriteIntToMemFile(34);

}

static unsafe void WriteIntToMemFile(int i)

{

using (var mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew("HZD20230925", 42))

using (var view = mmf.CreateViewAccessor())

{

byte* poke = null;

view.SafeMemoryMappedViewHandle.AcquirePointer(ref poke);

CopyMemory(new System.IntPtr(poke), new System.IntPtr(&i), sizeof(int));

view.SafeMemoryMappedViewHandle.AcquirePointer(ref poke);

int iRead = view.ReadInt32(0);

Debug.Assert(iRead == i);

}

}

DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory", CharSet = CharSet.Ansi)

public extern static long CopyMemory(IntPtr dest, IntPtr source, int size);

测试环境

Win7 VS2022

相关推荐
人工智能AI技术6 分钟前
C# 版 WorldSim 客户端:在 Unity 中连接 OpenAI 世界模拟器训练机器人
人工智能·c#
无心水12 分钟前
【文档解析】4、跨平台文档解析:JS/Go/C#全攻略
javascript·后端·golang·c#·架构师·大数据分析·分布式系统利器
武藤一雄9 小时前
C# 引用传递:深度解析 ref 与 out
windows·microsoft·c#·.net·.netcore
bugcome_com15 小时前
C# 高级集合使用示例
开发语言·c#
Mao_Hui15 小时前
Unity3d实时读取Modbus RTU数据
开发语言·嵌入式硬件·unity·c#
njsgcs16 小时前
怎么把面的类型特征,平面曲面融合进面邻接图或者图结构里
c#
爱炸薯条的小朋友16 小时前
C#依赖注入和仿写Prism注入
开发语言·c#
末点17 小时前
超长文本格式坐标串数据空间化入库
数据库·c#·st_geomfromtext