开发者

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

开发者 https://www.devze.com 2024-10-29 10:41 出处:网络 作者: lingxiao16888
创建一个多个程序共享的内存空间 /// <summary> /// 开辟本地自定义的共享内存区域类

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

/// <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,
                        android                    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),
                                       javascript     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;
 
      www.devze.com      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();
        }
    }
}

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

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#多程序共享内存内容请搜索编程编程客栈客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

精彩评论

暂无评论...
验证码 换一张
取 消