C#操作共享内存

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{

    class Program
    {
        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr CreateFile(string lpFileName,
            int dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes,
            int dwCreationDisposition, int dwFlagsAndAttributes,
            IntPtr hTemplateFile);

        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr CreateFileMapping(IntPtr hFile,
            IntPtr lpAttributes, int flProtect,
            int dwMaximumSizeLow, int dwMaximumSizeHigh, string lpName);
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr OpenFileMapping(int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName);
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr MapViewOfFile(IntPtr hFileMapping, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
        [DllImport("kernel32", EntryPoint = "GetLastError")]
        public static extern int GetLastError();
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaxSizeHi, uint dwMaxSizeLow, string lpName);
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool UnmapViewOfFile(IntPtr pvBaseAddress);
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);
        //原文链接:https://blog.csdn.net/gao271003105/article/details/81014094
        public const int FILE_MAP_READ = 0x0004;


        public static IntPtr fileMapping = IntPtr.Zero;
        public static IntPtr mapView = IntPtr.Zero;
        const int FILE_MAP_COPY = 0x0001;
        const int FILE_MAP_WRITE = 0x0002;
        // const int FILE_MAP_READ = 0x0004;
        const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;
        const int PAGE_READWRITE = 0x04;
        const int INVALID_HANDLE_VALUE = -1;
        const int ERROR_ALREADY_EXISTS = 183;
        private bool bValid;
        static bool m_bAlreadyExist = false;
        static bool m_bInit = false;
        static long m_MemSize = 0;
        public void ShareMemoryHelper(string name, uint length)
        {
            bValid = GetShareMemoryMap(name, length);
        }
        public void ShareMemoryHelper()
        {
        }
 
       // ~ShareMemoryHelper()
       // {
       //     Close();
       // }
        public bool GetShareMemoryMap(string name, uint length)
        {
            m_MemSize = length;
            fileMapping = OpenFileMapping(PAGE_READWRITE, false, name);
            if (fileMapping == IntPtr.Zero)
            {
                return false;
            }
            mapView = MapViewOfFile(fileMapping, (uint)FILE_MAP_READ, 0, 0, length);
            if (mapView == IntPtr.Zero)
            {
                int a = GetLastError();
                return false;
            }
            m_bInit = true;
            return true;
        }

        public static int CreateShareMemoryMap(string strName, long lngSize)
        {
            if (lngSize <= 0 || lngSize > 0x00800000) lngSize = 0x00800000;
            m_MemSize = lngSize;
            if (strName.Length > 0)
            {
                fileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)

PAGE_READWRITE, 0, (uint)lngSize, strName);
                if (fileMapping == IntPtr.Zero)
                {
                    return 2; 
                }
 
                if (GetLastError() == ERROR_ALREADY_EXISTS)
                {
                    m_bAlreadyExist = true;
                }
                else
                {
                    m_bAlreadyExist = false;
                }
                mapView = MapViewOfFile(fileMapping, FILE_MAP_WRITE, 0, 0, (uint)lngSize);
                if (mapView == IntPtr.Zero)
                {
                    m_bInit = false;
                    CloseHandle(fileMapping);
                    return 3; 
                }
                else
                {
                   m_bInit = true;
                    if (m_bAlreadyExist == false)
                    {
                    }
                }
            }
            else
            {
                return 1;
            }
            return 0;
        }
 
        public static int Write(byte[] bytData, int lngAddr, int lngSize)
        {
            if (lngAddr + lngSize > m_MemSize) return 2;
            if (m_bInit)
            {
                Marshal.Copy(bytData, lngAddr, mapView, lngSize);
            }
            else
            {
                return 1;
            }
            return 0;
        }
 
        public static int Read(ref byte[] bytData, int lngAddr, int lngSize)
        {
            if (lngAddr + lngSize > m_MemSize) return 2;
            if (m_bInit)
            {
                Marshal.Copy(mapView, bytData, lngAddr, lngSize);
            }
            else
            {
                return 1;
            }
            return 0;
        }
 
        public static void Close()
        {
            if (m_bInit)
            {
                UnmapViewOfFile(mapView);
                CloseHandle(fileMapping);
            }
        }
        static void Main(string[] args)
        {
            
            CreateShareMemoryMap("sss", 200);
            byte[] ss = { 0,0,0,0,0 };
            //Write(ss, 0, 2);
           int k= Read(ref ss, 0, 5);
            int st = ss[1];
            Console.ReadLine();
            Close();
            
        }
    }
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值