Developing a game ("jogo" in PT), the server can host up to 5 simultaneous games, which the client will access via mapped memory.
So here's what I have:
Server:
#define MAX_JOGOS 5
typedef struct{
...
} sJogo;
typedef struct{
sJogo * pS;
} sGlobals;
sJogo jogo[MAX_JOGOS]; //global
sGlobals globals[MAX_JOGOS]; //global
HANDLE hMapFile; //global
int _tmain(int argc, LPTSTR argv[]) {
...
hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(sJogo)*MAX_JOGOS, szName);
//create map for all games
....
}
//called when new game is created
void createView(int index){
//create view for 1 game and store pointer
//### need to apply offset here ###
globals.pS[index] = (sJogo * )MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(sJogo);
}
//called by thread on event set
void CopyJogo(int index){
//use stored pointer to update jogo
CopyMemory((PVOID)globals[index].pS, &jogo[index], sizeof(sJogo));
}
Client:
HANDLE hMapFile; //global
sJogo * pS; //global
int _tmain(int argc, LPTSTR argv[]) {
...
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szName);
pS = (sJogo *)MapViewOfFile(cdata.hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(sJogo));
//### need respective offset here ###
}
I have tried creating a view of "sizeof(sJogo)*MAX_JOGOS" and then incrementing the pointer+=sizeof(sJogo) * index; but didn't manage to succeed, so now I turn to you, can you help me learn to use the offset?
I have searched quite persistently and found a good example here on stackoverflow but it's C++ and I couldn't adapt it.
The high-order DWORD offset would be sizeof(sJogo) correct? But I don't know what granularity is or how to apply it to the low-order DWORD...
Can you help me? Thank you.
EDIT:
The code below is returning when i = 1 (NULL), what am I doing wrong?
int _tmain(int argc, LPTSTR argv[]) {
....
hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(sJogo)*MAX_JOGOS, szName);
if (hMapFile == NULL)
{...}
DWORD offset = 0;
for (i = 0; i < MAX_JOGOS; i++) {
if (MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, offset, sizeof(sJogo)) == NULL)
{
_tprintf(TEXT("Erro MapViewOfFile I: %d\n"), i);
CloseHandle(hMapFile);
return;
}
offset += sizeof(sJogo);
}
}
EDIT 2:
Solved the problem above, found the solution here:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa366548%28v=vs.85%29.aspx
I wasn't taking into account the allocation granularity on the offset, which was causing MapViewOfFile to return NULL on the second attempt.
The link above shows a clear example on how to apply it to the offset.