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

相关推荐
刘欣的博客11 小时前
C# 从API接口获取对象而不用先定义对象类
c#·json动态创建对象
Charles_go12 小时前
C#中级、double和decimal有什么区别
开发语言·c#
小熊熊知识库19 小时前
C#接入AI操作步骤详解(deepseek接入)
人工智能·flask·c#
玖笙&19 小时前
✨WPF编程进阶【7.3】集成动画(附源码)
c++·c#·wpf·visual studio
yue00821 小时前
C# 窗体渐变色
开发语言·javascript·c#
czhc114007566321 小时前
C#1119记录 类 string.Split type.TryParse(String,out type 变量)
android·c#
WangMing_X1 天前
C#一个项目实现文件目录常用操作(附源码完整)
开发语言·c#
mudtools1 天前
.NET集成飞书API最佳实践:基于Mud.Feishu的飞书二次开发实践
c#·.net
玩泥巴的1 天前
.NET项目中如何快速的集成飞书API
c#·.net·飞书
初九之潜龙勿用1 天前
C# 使用豆包 AI 模型实现首尾帧模式的视频生成
人工智能·microsoft·c#·ai编程·视频·ai模型·豆包