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

相关推荐
阿蒙Amon9 分钟前
C#常用类库-详解Moq
开发语言·c#·log4j
格林威14 分钟前
工业相机彩色图像采集:为什么我的图是绿色的?附海康/Basler/堡盟相机设置
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·工业相机
爱炸薯条的小朋友24 分钟前
C#使用反射,特性,表达式树仿写AutoMapper
开发语言·c#
似水明俊德32 分钟前
11-C#
开发语言·c#
人工智能AI技术1 小时前
.NET 9实战|最新C# AI Agent开发,Semantic Kernel+OpenClaw双剑合璧
人工智能·c#
我是唐青枫1 小时前
C#.NET stackalloc 深入解析:栈上分配、Span 配合与使用边界
c#·.net
一个帅气昵称啊1 小时前
.Net基于AgentFramework中智能体Agent Skill集成Shell命令实现小龙虾mini版
ai·c#·.net·openclaw
唐青枫2 小时前
深入理解 C#.NET Task.Run:调度原理、线程池机制与性能优化
c#·.net
金山几座16 小时前
C#学习记录-类(Class)
开发语言·学习·c#
The Shio18 小时前
OptiByte:一个可视化协议设计与多语言代码生成工具
网络·物联网·c#·.net·业界资讯