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

相关推荐
geovindu1 小时前
CSharp: Iterative Algorithms
开发语言·后端·算法·c#·.net·迭代算法
影寂ldy1 小时前
C# HttpClient 分片下载、断点续传、暂停取消(完整项目知识点)
开发语言·c#
code bean3 小时前
【C#】 主构造函数(Primary Constructors)的来龙去脉
开发语言·c#
Suxing93 小时前
C语言基础分享:“群租房”和“点名册”——联合体与枚举
c语言·算法·c#
czhc11400756634 小时前
725: [property: XmlIgnore]
c#
kingwebo'sZone4 小时前
C#事件声明办法
java·前端·c#
暖和_白开水6 小时前
数据分析agent(九):es_client_manager.py 和分词器ik_max_word问题
elasticsearch·数据分析·c#
Xin_ye100861 天前
第三章:内存泄漏的常见“案发现场”
c#·wpf
吴可可1231 天前
C#CAD点击计数器实现
c#
心平气和量大福大1 天前
C#-WPF-UserControl-生命周期(加载 退出)
开发语言·c#·wpf