【.NET进程通信】初探.NET中进程间通信的简单的实现
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【.NET进程通信】初探.NET中进程间通信的简单的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                轉載請注明出處:http://blog.csdn.net/xiaoy_h/article/details/26090277
廢話不多說,IPC就是進程間通信。
進程間通信能夠採用的方法非常多,比方創建port后採用組播技術進行握手連接,這里要講到的就是通過內存文件映射的方法實現。
先在項目中加入相關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="共享內存passwordFuck985211".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);轉載于:https://www.cnblogs.com/mengfanrong/p/4020504.html
總結
以上是生活随笔為你收集整理的【.NET进程通信】初探.NET中进程间通信的简单的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 石头智能洗地机 A10 Ultra 开启
- 下一篇: SQL之概念
