C#内存共享_内存共享库

C#内存共享一
2008年11月13日 星期四 下午 07:19
// 内存共享库
using System;
using System.Text;
using System.Collections;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;

namespace MQAD
{
    public class CShareMem
    {
        private IntPtr m_hMap;
        private IntPtr m_addr;
        const uint m_mapLength = 1024 * 256;

        public CShareMem(string shareName)
        {
            //m_hMap = CShareMem.OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, 0, shareName);

            m_hMap = CShareMem.CreateFileMapping((IntPtr)(-1), //HANDLE hFile,INVALID_HANDLE_VALUE = -1
            0,//LPSECURITY_ATTRIBUTES lpAttributes,        //0
            0x04,//DWORD flProtect,        PAGE_READWRITE = 0x04
            0,//DWORD dwMaximumSizeHigh,
            1024 * 256,//DWORD dwMaximumSizeLow,
            shareName //LPCTSTR lpName
            );
            if ((int)m_hMap > 0)
            {
                m_addr = CShareMem.MapViewOfFile(m_hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
            }
        }

        ~CShareMem()
        {
            if ((int)m_addr > 0)
            {
                UnmapViewOfFile(m_addr);
                CloseHandle(m_hMap);
            }
        }
        public IntPtr GetAddr()
        {
            return m_addr;
        }


        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
            int hWnd,    //目标窗口的handle
            int Msg,    // 消息
            int wParam, // 第一个消息参数
            ref COPYDATASTRUCT lParam // 第二个消息参数
            );

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string
            lpWindowName);

        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

        const int WM_COPYDATA = 0x004A;
        const int INVALID_HANDLE_VALUE = -1;
        const int PAGE_READWRITE = 0x04;


        //共享内存
        [DllImport("Kernel32.dll", EntryPoint = "CreateFileMapping")]
        public static extern IntPtr CreateFileMapping(IntPtr hFile,    //HANDLE hFile,INVALID_HANDLE_VALUE = -1
            UInt32 lpAttributes,//LPSECURITY_ATTRIBUTES lpAttributes,        //0
            UInt32 flProtect,//DWORD flProtect,        PAGE_READWRITE = 0x04
            UInt32 dwMaximumSizeHigh,//DWORD dwMaximumSizeHigh,
            UInt32 dwMaximumSizeLow,//DWORD dwMaximumSizeLow,
            string lpName//LPCTSTR lpName
            );

        [DllImport("Kernel32.dll", EntryPoint = "OpenFileMapping")]
        public static extern IntPtr OpenFileMapping(
            UInt32 dwDesiredAccess,//DWORD dwDesiredAccess,
            int bInheritHandle,//BOOL bInheritHandle,
            string lpName//LPCTSTR lpName
            );

        public const int FILE_MAP_ALL_ACCESS = 0x0002;
        public const int FILE_MAP_WRITE = 0x0002;
        public const int FILE_MAP_READ = 0x0004;

        [DllImport("Kernel32.dll", EntryPoint = "MapViewOfFile")]
        public static extern IntPtr MapViewOfFile(
            IntPtr hFileMappingObject,//HANDLE hFileMappingObject,
            UInt32 dwDesiredAccess,//DWORD dwDesiredAccess,    FILE_MAP_ALL_ACCESS Same as FILE_MAP_WRITE = 0x0002
            UInt32 dwFileOffsetHight,//DWORD dwFileOffsetHigh,
            UInt32 dwFileOffsetLow,//DWORD dwFileOffsetLow,
            UInt32 dwNumberOfBytesToMap//SIZE_T dwNumberOfBytesToMap
            );

        [DllImport("Kernel32.dll", EntryPoint = "UnmapViewOfFile")]
        public static extern int UnmapViewOfFile(IntPtr lpBaseAddress);

        [DllImport("Kernel32.dll", EntryPoint = "CloseHandle")]
        public static extern int CloseHandle(IntPtr hObject);

        //         [DllImport("shl2wapi.dll",EntryPoint="StrCpy")]
        //         private static extern string StrCpy(IntPtr psz1,string psz2);
        //         //LPTSTR StrCpy(LPTSTR psz1,LPCTSTR psz2);

        public unsafe void Copy(string src, IntPtr dst)
        {
            byte[] byteSrc = Encoding.Default.GetBytes(src);
            Copy(byteSrc, dst);
        }
        public void Clear()
        {
            if ((int)m_addr > 0)
            {
                byte[] b = new byte[m_mapLength];

                Copy(b, m_addr);
            }
        }

        public unsafe void Copy(byte[] byteSrc, IntPtr dst)
        {
            fixed (byte* pSrc = byteSrc)
            {
                byte* pDst = (byte*)dst;
                byte* psrc = pSrc;
                for (int i = 0; i < byteSrc.Length; i++)
                {
                    *pDst = *psrc;
                    pDst++;
                    psrc++;
                }
            }
        }

        public unsafe string GetString()
        {
            byte[] byteDst = new byte[1024 * 256];
            ArrayList arr = new ArrayList();

            int len = 0;
            fixed (byte* pd = byteDst)
            {
                byte* pSrc = (byte*)m_addr;
                byte* pDst = pd;
                for (int i = 0; (*pSrc) != '/0'; i++)
                {
                    *pDst = *pSrc;
                    arr.Add(*pSrc);

                    *pSrc = 0;

                    pDst++;
                    pSrc++;
                    len++;

                }
            }

            byte[] b = new byte[arr.Count];
            arr.CopyTo(b);

            string s = Encoding.Default.GetString(b);
            return s;

            //return Encoding.Default.GetString(byteDst);
        }
    }

    public class Win32Event
    {
        private string m_eventName = null;

        public Win32Event(string eventName)
        {
            m_eventName = eventName;
        }
        public Win32Event()
        {
            m_eventName = "";
        }

        //OPEN EVENT
        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern SafeWaitHandle OpenEvent(UInt32
            dwDesiredAccess, Boolean bInheritHandle, String lpName);

        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern SafeWaitHandle CreateEvent(IntPtr LPSECURITY_ATTRIBUTES, Boolean bManualReset, Boolean bInitialState, String lpName);
    }
}
阅读更多
上一篇Windows 进程间通信 共享内存(FileMapping)_C#实现
下一篇C#内存共享_服务端
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭