共享内存-矩阵映射
Shared memory - matrix mapping
我目前正在开发一个炸弹人游戏项目,其中应该有一个服务器,它有一个二维矩阵,以及1个或多个客户端。
我认为应该这样做的方式是通过在进程之间使用共享内存,其中客户端和"敌人"访问以获取有关表映射(矩阵)的信息并使用它。
问题是我不知道如何将指针映射到我的map对象(矩阵),以便其他进程可以获取该信息。
我从MSDN得到了这个函数,但我只解释到一个字符串:
//Server.cpp
//object creation (Matrix)
Mapa M(height, width);
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size(high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).n"),
GetLastError());
return 1;
}
**HANDLE hMapFile = &M; // will this work?**
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // <- How can I pass the object here?
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
请我如何映射一个指针到一个对象,甚至到一个对象,以便其他进程可以访问?
问候,
RC
要使用映射文件,您的服务器代码应该如下所示。请注意,我没有检查任何错误,以保持发布的代码简单(总是检查错误!)。
/* server */
HANDLE hFile;
HANDLE hMapFile;
hFile = CreateFile("test.dat",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
hMapFile = CreateFileMapping(hFile,
NULL,
PAGE_READWRITE,
0,
1024 * 1024,
"test.mapping"); // "mapping file name" of "test.dat"
/* keep server process running and do not close hFile or hMapFile */
你的客户端应该看起来像这样:
/* client */
HANDLE hMapFile;
char *pFile; // note: you can use any type of pointer here!
hMapFile = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE,
FALSE,
"test.mapping"); // same name as within CreateFileMapping(..)
if (hMapFile != NULL)
{
pFile = MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
1024 * 1024);
/* read pFile */
printf(pFile);
/* write pFile */
wsprintf(pFile, "Hallo?"); // <-- writes to test.dat!!
}
如前所述,如果用于服务器/客户端架构,这种设计将有一些缺点。我建议使用TCP/IP服务器/客户端,它的实现并不比命名管道更难。一个好的开始是运行Winsock客户端和服务器代码示例,但是网络上还有许多其他示例…
如果使用TCP/IP,您的应用程序将看起来像这样:
/* server */
// create listener socket
// while running
// accept new client(s)
// receive data from clients (if any data was received)
// react on data: (client sent 0x01 -> send matrix, ...)
/* client */
// create socket and connect to server
// send 0x01 command to obtain matrix
// receive response from server (= get matrix)
// do whatever your client does...
注意,0x01
是一个简单的命令字节,用于告诉服务器要做什么。您完全可以自由地告诉服务器要做什么。你也可以实现一个基于字符串的命令接口(例如客户端发送"get_matrix"而不是0x01)…
相关文章:
- 添加静态constexpr成员是否会更改结构/类的内存映射
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 字符串共享内存映射的向量
- 准确了解对象在内存中的映射方式
- 将布局映射到内存地址
- 确保内存映射页位于内存中
- <char> 使用 Vulkan 映射内存时如何使用 std::vector 而不是 void**?
- 我可以将新的 std::tuple 放入内存映射区域,并在以后读回吗?
- C++从 Java 角度设置和映射内存管理
- 如何在 OpenCL 中使用缓冲区分配和映射内存机制
- 两个进程之间的共享映射内存在编辑时未更新
- 频繁访问文件映射内存
- 由于动态数组而导致的哈希映射内存泄漏
- 映射和多映射:内存使用/管理差异
- 在自定义硬件上映射内存
- 内存映射内存是否可能
- 具有动态分配内存和映射内存的Shared_ptr
- mmap小尺寸内存,当munmap为glibc时,会将映射内存释放到操作系统
- C++ 标准::映射内存管理