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

相关推荐
rockey6272 小时前
AScript动态脚本多语言环境支持
sql·c#·.net·script·eval·function·动态脚本
ou.cs3 小时前
c# SemaphoreSlim保姆级教程
开发语言·网络·c#
龙侠九重天3 小时前
ML.NET 实战:快速构建分类模型
分类·数据挖掘·c#·.net
fengyehongWorld4 小时前
C# 创建Worker,杀死指定程序的线程
c#
Nuopiane8 小时前
C#基础(1)堆栈、GC与Marshal
unity·c#
FuckPatience8 小时前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
游乐码16 小时前
c#泛型约束
开发语言·c#
hoiii18716 小时前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
yongui4783418 小时前
C# 与三菱PLC通讯解决方案
开发语言·c#
jerryinwuhan20 小时前
RDD第二次练习
开发语言·c#