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

相关推荐
csdn_aspnet1 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore
csdn_aspnet1 天前
使用 C# .NETCore 实现MongoDB
mongodb·c#·.netcore
上位机付工1 天前
上位机通信速度有多快?
开发语言·c#·上位机·plc
FuckPatience1 天前
C# 修改基类List中某一元素的子类类型
c#·list
玉面小君1 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
_oP_i2 天前
WinForms 项目里生成时选择“首选目标平台 32 位导致有些电脑在获取office word对象时获取不到
c#·office
要记得喝水2 天前
C#某公司面试题(含题目和解析)--1
开发语言·windows·面试·c#·.net
冷冷的菜哥2 天前
ASP.NET Core文件分片上传
c#·asp.net·asp.net core·文件分片上传