简体   繁体   中英

C - shared memory cast to struct

I've got to finish my C program, however I'm stuck on the Shared memory part of the task.

Basically this is what I should do: MapViewOfFile returns a pointer to void which you can cast to anything you like. I suggest you create struct to represent the structure you would like the memory to have and cast the return pointer to this struct."

I call the MapViewOffFile function, but I don't understand how I'm supposed to point the struct to it. Code:

typedef struct {
        LARGE_INTEGER start;
        LARGE_INTEGER end;
        LARGE_INTEGER frq;
} TimeOfSharing;

TimeOfSharing timing;

HANDLE fileView;
fileView = MapViewOfFile(fileHandle, FILE_MAP_READ | FILE_MAP_WRITE,PAGE_READONLY, 0, 0);

So how do I point the fileView to my struct? (I need to fetch the struct from another process)

Hope I was clear enough! Thanks a lot!

MapViewOfFile actually returns a pointer to void, not a HANDLE .

You just need to cast that appropriately:

TimeOfSharing *timing = (TimeOfSharing *)MapViewOfFile(...);

// Then access as you see fit, e.g.:
LARGE_INTEGER length;

length.QuadPart = timing->end.QuadPart - timing->start.QuadPart;

If you really need/want to actually copy the data, not just access it in place:

TimeOfSharing my_copy = *(TimeOfSharing *)MapViewOfFile(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM