【.NET进程通信】初探.NET中进程间通信的简单的实现

转载请注明出处:http://blog.csdn.net/xiaoy_h/article/details/26090277

废话不多说,IPC就是进程间通信。

进程间通信可以采用的方法很多,比如创建端口后采用组播技术进行握手连接,这里要讲到的就是通过内存文件映射的方法实现。

先在项目中添加相关API函数:

        [DllImport("kernel32.dll", EntryPoint = "OpenFileMapping", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr OpenFileMapping(uint dwDesiredAccess, bool bInheritHandle, String lpName);
        [DllImport("Kernel32.dll")]
        private static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
        [DllImport("Kernel32.dll", EntryPoint = "UnmapViewOfFile", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
        [DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern bool CloseHandle(IntPtr hHandle);
        [DllImport("Kernel32.dll", EntryPoint = "CreateFileMapping", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr CreateFileMapping(uint hFile, IntPtr lpAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
        
然后在共享端添加代码:

            string shareName = "XiaoY_H的内存共享";
            char[] myShrCntnt="共享内存密码Fuck985211".ToCharArray();
            IntPtr hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, PAGE_READWRITE, 0, 256, shareName);
            IntPtr pBuf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 256);
            Marshal.Copy(myShrCntnt, 0, pBuf, myShrCntnt.Length);
            
            Console.WriteLine("共享内存建立完毕,它就在这儿:IntPtr->{0:G}",pBuf.ToInt32());
            Console.ReadKey();
            UnmapViewOfFile(pBuf);
            CloseHandle(hMapFile);                   
在被共享端添加代码:

            string shareName = "XiaoY_H的内存共享";
            IntPtr hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, shareName);
            if (hMapFile==IntPtr.Zero)
            {
                Console.WriteLine("Null MapFile!");
                return;
            }
            IntPtr pBuf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 256);
            if (pBuf==IntPtr.Zero)
            {
                Console.WriteLine("Null Buffer!");
                return;
            }
            Console.WriteLine("共享内存数据:" + Marshal.PtrToStringUni(pBuf));
            Console.ReadKey();
            UnmapViewOfFile(pBuf);
            CloseHandle(hMapFile);        




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值