1

In this topic Two variables in one shared memory , you can see how to put 2 variables into one shared memory in C.

However, I want to put multiple variables into one shared memory using MapViewOfFile function. But there's no example or solution I've found. Types of variables are different so I can't use std::vector nor array.

How should I set arguments of CreateFileMapping and MapViewOfFile to do this? How can I get and set an address in FileMapping which I want to read and write a variable?

It shouldn't be needed that I have to create a FileMapping for each variables, right?

uehara1124
  • 11
  • 1

3 Answers3

1

Use a struct as davetherock pointed out. You have to specify the total size of all the members for "CreateFileMapping" and for "MapViewOfFile". Then you can cast the return void pointer of MapViewOfFile to the structure pointer type.

For example, if you have a struct like

typedef struct combinedStruct {
    int intVariable;
    float floatVariable;
}CombinedStruct; 

You have to create a pointer of type CombinedStruct and cast the return of MapViewOfFile.

CombinedStruct * structPtr = (CombinedStruct*)(MapViewOfFile(...));

Then you can access the individual variables like structPtr->intVariable and structPtr->floatVariable

Manoj AV
  • 119
  • 4
1

This may be better suited as comment but i do not have enough reputation to comment. I am also looking for the answer for this same question and i did as said by @Manoj AV , with one change-

In the CopyMemory Instead of retrieving it as structPtr->intVariable and structPtr->floatVariable i used structPtrfor first variable and structPtr+1 to retrieve the second variable in the structure and so on.And it runs successfully.

watson
  • 53
  • 6
0

The easiest way to have two variables back-to-back in the same chunk of memory is to use a Struct: typedef struct vs struct definitions. If you'd like to use shmget, you simply must adjust the size of the memory allocated

shmid = shmget (shmkey, sizeof(var1) + sizeof(var2), 0644 | IPC_CREAT);

Then, adjust the pointers as necessary.

davetherock
  • 224
  • 1
  • 2
  • 12