C#自定义实现多程序共享内存空间

 更新时间:2024年10月28日 09:18:48   作者:lingxiao16888  
这篇文章主要为大家详细介绍了C#如何自定义实现多程序共享内存空间,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

创建一个多个程序共享的内存空间

/// <summary>
    /// 开辟本地自定义的共享内存区域类
    /// </summary>
    public class MCimSharedMemory<T> : IDisposable where T : new()
    {
        /// <summary>
        /// 自定义的内存区域的名
        /// </summary>
        public readonly string MapName = @"Local\CimSharedMemory";
        private MemoryMappedFileSecurity FileSecurity = null;
        private MemoryMappedFile MemoryMapped = null;
        /// <summary>
        /// 可随机访问的内存块
        /// </summary>
        private MemoryMappedViewAccessor MemoryAccessor = null;
        private int Capacity = 0;
 
        public T Value { get; set; }
 
        /// <summary>
        ///  开辟本地自定义的共享内存区域类构造方法
        /// </summary>
        public MCimSharedMemory()
        {
            this.FileSecurity = new MemoryMappedFileSecurity();
            this.FileSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, AccessControlType.Allow));
 
            // Memory Map 
            this.Value = new T();
 
            // 获取结构体大小
            this.Capacity = Marshal.SizeOf(typeof(T));
        }
 
        /// <summary>
        /// 析构函数
        /// </summary>
        ~MCimSharedMemory()
        {
            Dispose();
        }
 
        /// <summary>
        /// 创建并打开自定义的本地共享内存区域
        /// </summary>
        public void CreateOrOpenSharedMemory()
        {
            this.MemoryMapped = MemoryMappedFile.CreateOrOpen(this.MapName,
                                            this.Capacity,
                                            MemoryMappedFileAccess.ReadWriteExecute,
                                            MemoryMappedFileOptions.None,
                                            this.FileSecurity,
                                            HandleInheritability.Inheritable);
 
            this.MemoryAccessor = this.MemoryMapped.CreateViewAccessor();
        }
        /// <summary>
        /// 从文件创建自定义的共享内存区域
        /// </summary>
        public void CreateFromFileSharedMemory()
        {
            this.MemoryMapped = MemoryMappedFile.CreateFromFile(new FileStream(@"", FileMode.Create),
                                            this.MapName,
                                            this.Capacity,
                                            MemoryMappedFileAccess.ReadWriteExecute,
                                            this.FileSecurity,
                                            HandleInheritability.Inheritable,
                                            true);
 
            this.MemoryAccessor = this.MemoryMapped.CreateViewAccessor();
        }
 
       
        public void CreateSharedMemory()
        {
            this.MemoryMapped = MemoryMappedFile.CreateNew(this.MapName,
                                            this.Capacity,
                                            MemoryMappedFileAccess.ReadWriteExecute,
                                            MemoryMappedFileOptions.None,
                                            this.FileSecurity,
                                            HandleInheritability.Inheritable);
 
            this.MemoryAccessor = this.MemoryMapped.CreateViewAccessor();
        }
 
        /// <summary>
        /// 打开自定义的共享内存区域
        /// </summary>
        public void OpenSharedMemory()
        {
            this.MemoryMapped = MemoryMappedFile.OpenExisting(this.MapName);
            this.MemoryAccessor = this.MemoryMapped.CreateViewAccessor();
        }
        /// <summary>
        /// 读取自定义的共享内存区域
        /// </summary>
        /// <returns></returns>
        public T ReadMemory()
        {
            byte[] bytes = new byte[this.Capacity];
 
            // Initialize unmanaged memory.
            IntPtr p = Marshal.AllocHGlobal(this.Capacity);
 
            // Read from memory mapped file.
            this.MemoryAccessor.ReadArray<byte>(0, bytes, 0, bytes.Length);
 
            // Copy from byte array to unmanaged memory.
            Marshal.Copy(bytes, 0, p, this.Capacity);
 
            // Copy unmanaged memory to struct.
            T ReadData = (T)Marshal.PtrToStructure(p, typeof(T));
 
            // Free unmanaged memory.
            Marshal.FreeHGlobal(p);
            p = IntPtr.Zero;
 
            // Value assign
            this.Value = ReadData;
 
            return ReadData;
        }
        /// <summary>
        /// 向随机内存写入值
        /// </summary>
        public void WriteMemory()
        {
            byte[] bytes = new byte[this.Capacity];
 
            // Initialize unmanaged memory.
            IntPtr p = Marshal.AllocHGlobal(this.Capacity);
 
            // Copy struct to unmanaged memory.
            Marshal.StructureToPtr(this.Value, p, false);
 
            // Copy from unmanaged memory to byte array.
            Marshal.Copy(p, bytes, 0, this.Capacity);
 
            this.MemoryAccessor.WriteArray<byte>(0, bytes, 0, bytes.Length);
 
            // Free unmanaged memory.
            Marshal.FreeHGlobal(p);
            p = IntPtr.Zero;
        }
 
        public void Dispose()
        {
            if (this.MemoryAccessor != null)
            {
                this.MemoryAccessor.Dispose();
                this.MemoryAccessor = null;
            }
 
            if (MemoryMapped != null)
            {
                this.MemoryMapped.Dispose();
                this.MemoryMapped = null;
            }
        }
    }
  
 
    [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
    public class SCimMemory
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0xFFFF)] public short[] Bit;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FFFF)] public short[] Word;
 
        public SCimMemory()
        {
            this.Bit = new short[0xFFFF];
            this.Word = new short[0x3FFFF];
        }
    }

应用。

A程序:填充自定义内存空间

namespace 共享内存区域1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("共享区域");
            MCimSharedMemory<SCimMemory> memory = new MCimSharedMemory<SCimMemory>();
            memory.CreateOrOpenSharedMemory();
            Console.WriteLine("写入值");
            memory.Value = new SCimMemory();
            memory.Value.Bit[0] = 100;
            memory.Value.Word[0] = 120;
            memory.WriteMemory();
            
            Console.WriteLine("输入完成");
            Console.ReadKey();
        }
    }
}

B程序:读取自定义共享内存数据。

namespace 共享内存区域2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("共享区域");
            MCimSharedMemory<SCimMemory> memory = new MCimSharedMemory<SCimMemory>();
            memory.CreateOrOpenSharedMemory();
            Console.WriteLine("读取值");
            memory.ReadMemory();
            Console.WriteLine($"B0={memory.Value.Bit[0]},W0={memory.Value.Word[0]}");
 
            Console.WriteLine("输入完成");
            Console.ReadKey();
        }
    }
}

到此这篇关于C#自定义实现多程序共享内存空间的文章就介绍到这了,更多相关C#多程序共享内存内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • c#自带缓存使用方法 c#移除清理缓存

    c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下
    2014-02-02
  • C#获取Description特性的扩展类详解

    C#获取Description特性的扩展类详解

    这篇文章主要和大家详细介绍一下C#获取Description特性的扩展类,文中的示例代码讲解详细,对我们学习有一定的帮助,需要的可以参考一下
    2022-06-06
  • C#异常处理的技巧和方法

    C#异常处理的技巧和方法

    在本篇文章里小编给大家整理了关于C#异常处理的技巧和方法以及相关知识点,需要的朋友们学习下。
    2019-03-03
  • C# 实现把double 存成两位精度小数

    C# 实现把double 存成两位精度小数

    这篇文章主要介绍了C# 实现把double 存成两位精度小数,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • C# List介绍及具体用法

    C# List介绍及具体用法

    这篇文章主要介绍了C# List介绍及具体用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • c#栈变化规则图解示例(栈的生长与消亡)

    c#栈变化规则图解示例(栈的生长与消亡)

    多数情况下我们不需要关心栈的变化,下文会给出一个具体的示例。另外,理解栈的变化对于理解作用域也有一定的好处,因为C#的局部变量作用域是基于栈的。
    2013-11-11
  • C#自定义基于控制台的Timer实例

    C#自定义基于控制台的Timer实例

    这篇文章主要介绍了C#自定义基于控制台的Timer实现方法,可以简单模拟timer控件的相关功能,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-08-08
  • C# Winform TextBox控件多行输入方式

    C# Winform TextBox控件多行输入方式

    这篇文章主要介绍了C# Winform TextBox控件多行输入方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • WinForm开发中屏蔽WebBrowser脚本错误提示的方法

    WinForm开发中屏蔽WebBrowser脚本错误提示的方法

    这篇文章主要介绍了WinForm开发中屏蔽WebBrowser脚本错误提示的方法,在C#项目开发中比较实用,需要的朋友可以参考下
    2014-08-08
  • C#使用ILGenerator动态生成函数的简单代码

    C#使用ILGenerator动态生成函数的简单代码

    这篇文章主要介绍了C#使用ILGenerator动态生成函数的简单代码,需要的朋友可以参考下
    2017-08-08

最新评论