Win32SharedMemory.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #ifdef _WIN32
  2. #include "Win32SharedMemory.h"
  3. #include "Bullet3Common/b3Logging.h"
  4. #include "Bullet3Common/b3Scalar.h"
  5. #include <windows.h>
  6. //see also https://msdn.microsoft.com/en-us/library/windows/desktop/aa366551%28v=vs.85%29.aspx
  7. //TCHAR szName[]=TEXT("Global\\MyFileMappingObject2");
  8. TCHAR szName[]=TEXT("MyFileMappingObject2");
  9. struct Win32SharedMemoryInteralData
  10. {
  11. HANDLE m_hMapFile;
  12. void* m_buf;
  13. Win32SharedMemoryInteralData()
  14. :m_hMapFile(0),
  15. m_buf(0)
  16. {
  17. }
  18. };
  19. Win32SharedMemory::Win32SharedMemory()
  20. {
  21. m_internalData = new Win32SharedMemoryInteralData;
  22. }
  23. Win32SharedMemory::~Win32SharedMemory()
  24. {
  25. delete m_internalData;
  26. }
  27. void* Win32SharedMemory::allocateSharedMemory(int key, int size, bool allowCreation)
  28. {
  29. b3Assert(m_internalData->m_buf==0);
  30. m_internalData->m_hMapFile = OpenFileMapping(
  31. FILE_MAP_ALL_ACCESS, // read/write access
  32. FALSE, // do not inherit the name
  33. szName); // name of mapping object
  34. if (m_internalData->m_hMapFile==NULL)
  35. {
  36. if (allowCreation)
  37. {
  38. m_internalData->m_hMapFile = CreateFileMapping(
  39. INVALID_HANDLE_VALUE, // use paging file
  40. NULL, // default security
  41. PAGE_READWRITE, // read/write access
  42. 0, // maximum object size (high-order DWORD)
  43. size, // maximum object size (low-order DWORD)
  44. szName); // name of mapping object
  45. } else
  46. {
  47. b3Error("Could not create file mapping object (%d).\n",GetLastError());
  48. return 0;
  49. }
  50. }
  51. m_internalData->m_buf = MapViewOfFile(m_internalData->m_hMapFile, // handle to map object
  52. FILE_MAP_ALL_ACCESS, // read/write permission
  53. 0,
  54. 0,
  55. size);
  56. if (m_internalData->m_buf == NULL)
  57. {
  58. b3Error("Could not map view of file (%d).\n",GetLastError());
  59. CloseHandle(m_internalData->m_hMapFile);
  60. return 0;
  61. }
  62. return m_internalData->m_buf;
  63. }
  64. void Win32SharedMemory::releaseSharedMemory(int key, int size)
  65. {
  66. if (m_internalData->m_buf)
  67. {
  68. UnmapViewOfFile(m_internalData->m_buf);
  69. m_internalData->m_buf=0;
  70. }
  71. if (m_internalData->m_hMapFile)
  72. {
  73. CloseHandle(m_internalData->m_hMapFile);
  74. m_internalData->m_hMapFile = 0;
  75. }
  76. }
  77. Win32SharedMemoryServer::Win32SharedMemoryServer()
  78. {
  79. }
  80. Win32SharedMemoryServer::~Win32SharedMemoryServer()
  81. {
  82. }
  83. Win32SharedMemoryClient::Win32SharedMemoryClient()
  84. {
  85. }
  86. Win32SharedMemoryClient:: ~Win32SharedMemoryClient()
  87. {
  88. }
  89. #endif //_WIN32