背景
多个进程直接需要传递大量图片,所以对性能要求较高。支付复制内存显然比转成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