进程间通信——共享内存

举报
AI浩 发表于 2021/12/22 23:12:51 2021/12/22
【摘要】 接收端 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Runtime.InteropSer...

接收端


  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. namespace WindowsFormsApp1
  13. {
  14. public partial class Form1 : Form
  15. {
  16. const int INVALID_HANDLE_VALUE = -1;
  17. const int PAGE_READWRITE = 0x04;
  18. [DllImport("User32.dll")]
  19. private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  20. [DllImport("User32.dll")]
  21. private static extern bool SetForegroundWindow(IntPtr hWnd);
  22. //共享内存
  23. [DllImport("Kernel32.dll", EntryPoint = "CreateFileMapping")]
  24. private static extern IntPtr CreateFileMapping(IntPtr hFile, //HANDLE hFile,
  25. UInt32 lpAttributes,//LPSECURITY_ATTRIBUTES lpAttributes, //0
  26. UInt32 flProtect,//DWORD flProtect
  27. UInt32 dwMaximumSizeHigh,//DWORD dwMaximumSizeHigh,
  28. UInt32 dwMaximumSizeLow,//DWORD dwMaximumSizeLow,
  29. string lpName//LPCTSTR lpName
  30. );
  31. [DllImport("Kernel32.dll", EntryPoint = "OpenFileMapping")]
  32. private static extern IntPtr OpenFileMapping(
  33. UInt32 dwDesiredAccess,//DWORD dwDesiredAccess,
  34. int bInheritHandle,//BOOL bInheritHandle,
  35. string lpName//LPCTSTR lpName
  36. );
  37. const int FILE_MAP_ALL_ACCESS = 0x0002;
  38. const int FILE_MAP_WRITE = 0x0002;
  39. [DllImport("Kernel32.dll", EntryPoint = "MapViewOfFile")]
  40. private static extern IntPtr MapViewOfFile(
  41. IntPtr hFileMappingObject,//HANDLE hFileMappingObject,
  42. UInt32 dwDesiredAccess,//DWORD dwDesiredAccess
  43. UInt32 dwFileOffsetHight,//DWORD dwFileOffsetHigh,
  44. UInt32 dwFileOffsetLow,//DWORD dwFileOffsetLow,
  45. UInt32 dwNumberOfBytesToMap//SIZE_T dwNumberOfBytesToMap
  46. );
  47. [DllImport("Kernel32.dll", EntryPoint = "UnmapViewOfFile")]
  48. private static extern int UnmapViewOfFile(IntPtr lpBaseAddress);
  49. [DllImport("Kernel32.dll", EntryPoint = "CloseHandle")]
  50. private static extern int CloseHandle(IntPtr hObject);
  51. private Semaphore m_Write; //可写的信号
  52. private Semaphore m_Read; //可读的信号
  53. private IntPtr handle; //文件句柄
  54. private IntPtr addr; //共享内存地址
  55. uint mapLength; //共享内存长
  56. //线程用来读取数据
  57. Thread threadRed;
  58. public Form1()
  59. {
  60. InitializeComponent();
  61. init();
  62. }
  63. ///<summary>/// 初始化共享内存数据 创建一个共享内存
  64. ///</summary>
  65. private void init()
  66. {
  67. m_Write = new Semaphore(1, 1, "WriteMap");//开始的时候有一个可以写
  68. m_Read = new Semaphore(0, 1, "ReadMap");//没有数据可读
  69. mapLength = 1024;
  70. IntPtr hFile = new IntPtr(INVALID_HANDLE_VALUE);
  71. handle = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, mapLength, "shareMemory");
  72. addr = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
  73. threadRed = new Thread(new ThreadStart(ThreadReceive));
  74. threadRed.Start();
  75. }
  76. /// <summary>
  77. /// 线程启动从共享内存中获取数据信息
  78. /// </summary>
  79. private void ThreadReceive()
  80. {
  81. while (true)
  82. {
  83. try
  84. {
  85. //读取共享内存中的数据:
  86. //是否有数据写过来
  87. m_Read.WaitOne();
  88. //IntPtr m_Sender = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
  89. byte[] byteStr = new byte[100];
  90. byteCopy(byteStr, addr);
  91. string str = Encoding.Default.GetString(byteStr, 0, byteStr.Length);
  92. this.Invoke((MethodInvoker)(delegate ()
  93. { textBox1.Text = str.Trim(); })
  94. );
  95. /调用数据处理方法 处理读取到的数据
  96. m_Write.Release();
  97. }
  98. catch (WaitHandleCannotBeOpenedException)
  99. {
  100. continue;
  101. //Thread.Sleep(0);
  102. }
  103. }
  104. }
  105. //不安全的代码在项目生成的选项中选中允许不安全代码
  106. static unsafe void byteCopy(byte[] dst, IntPtr src)
  107. {
  108. fixed (byte* pDst = dst)
  109. {
  110. byte* pdst = pDst;
  111. byte* psrc = (byte*)src;
  112. while ((*pdst++ = *psrc++) != '\0')
  113. ;
  114. }
  115. }
  116. }
  117. }

 

发送端

 


  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. namespace WindowsFormsApp2
  13. {
  14. public partial class Form1 : Form
  15. {
  16. const int INVALID_HANDLE_VALUE = -1;
  17. const int PAGE_READWRITE = 0x04;
  18. //共享内存
  19. [DllImport("Kernel32.dll", EntryPoint = "CreateFileMapping")]
  20. private static extern IntPtr CreateFileMapping(IntPtr hFile, //HANDLE hFile,
  21. UInt32 lpAttributes,//LPSECURITY_ATTRIBUTES lpAttributes, //0
  22. UInt32 flProtect,//DWORD flProtect
  23. UInt32 dwMaximumSizeHigh,//DWORD dwMaximumSizeHigh,
  24. UInt32 dwMaximumSizeLow,//DWORD dwMaximumSizeLow,
  25. string lpName//LPCTSTR lpName
  26. );
  27. [DllImport("Kernel32.dll", EntryPoint = "OpenFileMapping")]
  28. private static extern IntPtr OpenFileMapping(
  29. UInt32 dwDesiredAccess,//DWORD dwDesiredAccess,
  30. int bInheritHandle,//BOOL bInheritHandle,
  31. string lpName//LPCTSTR lpName
  32. );
  33. const int FILE_MAP_ALL_ACCESS = 0x0002;
  34. const int FILE_MAP_WRITE = 0x0002;
  35. [DllImport("Kernel32.dll", EntryPoint = "MapViewOfFile")]
  36. private static extern IntPtr MapViewOfFile(
  37. IntPtr hFileMappingObject,//HANDLE hFileMappingObject,
  38. UInt32 dwDesiredAccess,//DWORD dwDesiredAccess
  39. UInt32 dwFileOffsetHight,//DWORD dwFileOffsetHigh,
  40. UInt32 dwFileOffsetLow,//DWORD dwFileOffsetLow,
  41. UInt32 dwNumberOfBytesToMap//SIZE_T dwNumberOfBytesToMap
  42. );
  43. [DllImport("Kernel32.dll", EntryPoint = "UnmapViewOfFile")]
  44. private static extern int UnmapViewOfFile(IntPtr lpBaseAddress);
  45. [DllImport("Kernel32.dll", EntryPoint = "CloseHandle")]
  46. private static extern int CloseHandle(IntPtr hObject);
  47. private Semaphore m_Write; //可写的信号
  48. private Semaphore m_Read; //可读的信号
  49. private IntPtr handle; //文件句柄
  50. private IntPtr addr; //共享内存地址
  51. uint mapLength; //共享内存长
  52. Thread threadRed;
  53. public Form1()
  54. {
  55. InitializeComponent();
  56. //threadRed = new Thread(new ThreadStart(init));
  57. //threadRed.Start();
  58. mapLength = 1024;
  59. }
  60. private void button1_Click(object sender, EventArgs e)
  61. {
  62. try
  63. {
  64. m_Write = Semaphore.OpenExisting("WriteMap");
  65. m_Read = Semaphore.OpenExisting("ReadMap");
  66. handle = OpenFileMapping(FILE_MAP_WRITE, 0, "shareMemory");
  67. addr = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
  68. m_Write.WaitOne();
  69. byte[] sendStr = Encoding.Default.GetBytes(textBox1.Text.ToString() + '\0');
  70. //如果要是超长的话,应另外处理,最好是分配足够的内存
  71. if (sendStr.Length < mapLength)
  72. Copy(sendStr, addr);
  73. m_Read.Release();
  74. }
  75. catch (WaitHandleCannotBeOpenedException)
  76. {
  77. MessageBox.Show("不存在系统信号量!");
  78. return;
  79. }
  80. }
  81. static unsafe void Copy(byte[] byteSrc, IntPtr dst)
  82. {
  83. fixed (byte* pSrc = byteSrc)
  84. {
  85. byte* pDst = (byte*)dst;
  86. byte* psrc = pSrc;
  87. for (int i = 0; i < byteSrc.Length; i++)
  88. {
  89. *pDst = *psrc;
  90. pDst++;
  91. psrc++;
  92. }
  93. }
  94. }
  95. }
  96. }

 

文章来源: wanghao.blog.csdn.net,作者:AI浩,版权归原作者所有,如需转载,请联系作者。

原文链接:wanghao.blog.csdn.net/article/details/112003475

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。