创建和读写内存映射文件,用于同电脑上不同软件之间进行数据交互

在C#中,MemoryMappedFile 类允许你创建或打开一个内存映射文件,而 ViewAccessor 类则提供了一种方法来访问该文件的特定部分。以下是一个完整的示例,展示了如何创建或打开一个内存映射文件,如何使用 ViewAccessor 进行读写操作,以及如何查询数据。

示例代码:

csharp 复制代码
using System;  
using System.IO.MemoryMappedFiles;  
using System.Runtime.InteropServices;  
  
class Program  
{  
    // 内存映射文件的名称  
    private const string mapName = "exampleMap";  
    // 内存映射文件的大小(以字节为单位)  
    private const int mapSize = 1024;  
    // 要写入的数据的起始地址(偏移量)  
    private const int startOffset = 0;  
  
    static void Main()  
    {  
        // 创建或打开内存映射文件  
        using (var mmf = MemoryMappedFile.CreateOrOpen(mapName, mapSize))  
        {  
            // 创建一个视图访问器,用于读写操作  
            using (var accessor = mmf.CreateViewAccessor(startOffset, mapSize))  
            {  
                // 写入数据(整数)  
                int dataToWrite = 42;  
                accessor.Write(0, dataToWrite);  
  
                // 读取数据(整数)  
                int dataRead = accessor.ReadInt32(0);  
                Console.WriteLine($"Read data: {dataRead}");  
  
                // 写入数据(布尔值,注意布尔值通常占用1位,但这里为了简单起见,我们写入一个字节)  
                bool boolValueToWrite = true;  
                byte boolByte = boolValueToWrite ? (byte)1 : (byte)0;  
                accessor.Write(4, boolByte);  
  
                // 读取数据(布尔值)  
                byte boolByteRead = accessor.ReadByte(4);  
                bool boolValueRead = boolByteRead == 1;  
                Console.WriteLine($"Read bool data: {boolValueRead}");  
  
                // 写入数据(字符串,注意字符串需要序列化为字节数组)  
                string strToWrite = "Hello";  
                byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(strToWrite);  
                accessor.WriteArray(8, strBytes, 0, strBytes.Length);  
  
                // 读取数据(字符串)  
                byte[] strBytesRead = new byte[strBytes.Length];  
                accessor.ReadArray(8, strBytesRead, 0, strBytesRead.Length);  
                string strRead = System.Text.Encoding.UTF8.GetString(strBytesRead);  
                Console.WriteLine($"Read string data: {strRead}");  
            }  
        }  
  
        // 注意:当 using 块结束时,内存映射文件和视图访问器都会被自动关闭和释放。  
    }  
}
相关推荐
qq_529835351 小时前
对计算机中缓存的理解和使用Redis作为缓存
数据库·redis·缓存
阿桢呀14 小时前
Redis实战篇《黑马点评》5
数据库·redis·缓存
01_14 小时前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
Kerwin要坚持日更15 小时前
一文讲解Redis中的主从复制
数据库·redis·缓存
Suk-god15 小时前
【Redis】基础知识入门
数据库·redis·缓存
guihong00421 小时前
Redis 深度解析:高性能缓存与分布式数据存储的核心利器
redis·分布式·缓存
qq_529835351 天前
Redis作为缓存和数据库的数据一致性问题
数据库·redis·缓存
艾斯比的日常1 天前
提升接口性能之缓存
缓存
想要打 Acm 的小周同学呀1 天前
Redis三剑客解决方案
数据库·redis·缓存
HBryce241 天前
CPU多级缓存与缓存一致性协议
缓存