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

相关推荐
李高钢43 分钟前
REST vs gRPC 选型对比与迁移实践:从原理到落地
c#·集成·winforms
一个帅气昵称啊2 小时前
.Net C# AI智能体开发-快速开始
开发语言·c#·.net
半亩码田5 小时前
C#转Python第3.6篇:Python 的 @property 比 C# 的 get/set 更灵活
java·python·c#
楠楠子呀10 小时前
独立站聊天转化全链路:从二维码引流到数据复盘
java·javascript·数据仓库·python·c#·自动化·etl
csdn_aspnet11 小时前
C# 第k个最小元素(K’th Smallest Element)
算法·c#·排序算法
影寂ldy11 小时前
Modbus-ASCII 协议 + LRC校验
笔记·网络协议·c#
自己的九又四分之三站台12 小时前
C# 接入 RasterLite2:从原生 DLL 加载到 Coverage、Section、Tile 验证
开发语言·c#·地理信息
好名字都被猪取了-12 小时前
# C# 全栈开发资源包(.NET8/.NET10)
c#
淡海水13 小时前
03-05-线性-Array-List-LinkedList与Span-所有权与成本模型选型
c#·list·编译·array·clr·机器码
瓜皮弟子头很铁14 小时前
使用c#程序打开windows软件
c#