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

相关推荐
格林威2 分钟前
工业相机图像高速存储(C#版):直接IO(Direct I/O)方法,附Basler相机实战代码!
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
顾温3 分钟前
c# 多线程
开发语言·c#
格林威17 分钟前
工业相机图像高速存储(C#版):直接IO存储方法,附海康相机C#实战代码!
开发语言·人工智能·数码相机·c#·工业相机·海康相机·堡盟相机
csdn_aspnet21 分钟前
使用 Ollama,通过 C#、语义内核和 Google Gemma 3 构建本地 AI 代理
人工智能·ai·c#·ollama·gemma
唐青枫39 分钟前
C#.NET ReadOnlySequence 深入解析:多段内存遍历与零拷贝协议解析
c#·.net
废嘉在线抓狂.1 小时前
TimeLine如何自定义轨道
unity·c#·对话系统
hixiong12311 小时前
C# OpenvinoSharp使用RAD进行缺陷检测
开发语言·人工智能·c#·openvino
InCerry11 小时前
C# .NET 周刊|2026年2月4期
c#·.net周报·.net周刊
刘欣的博客12 小时前
C# 发送飞书webhook消息
c#·飞书·发消息