1

I have used CreateFileMapping and MapViewOfFile to map a file under Window using C++ VS2010.

The only way to get / read data from this mapped file that I know is to use MemCpy. However, I was hoping that there might be a faster / more direct way.

Is there one? If yes, could somebody please post a sample?

Thank you!

1
  • Memcpy() requires a pointer to the view. Just use that pointer directly. This quacks like an XY question. You could only ask this if you have trouble with arbitrating access to the view. A named semaphore is required to prevent your app from accessing the view while the other process is updating it. Life is a lot easier with a pipe. Commented Sep 18, 2013 at 14:47

1 Answer 1

2

you may cast the memory block to a data struct, as a pointer,

struct someStruct* data = (struct someStruct*)memAddress; 

then you can access the data as a pointer

somefuction (data->var1, data->var2); 

or

sum = data->var1 + data->var2; 

you will have to be carful, and sure that the mapping struct matches the memory block, or you gonna get some junk

something like this

struct msgStructureCommon { unsigned int messageID; unsigned int messageSize; char bufferLimit[1024-(2*sizeof(unsigned int))]; };

struct msgStructureID911 { unsigned int messageID; unsigned int messageSize; //someData.... }; struct msgStructureID2013 { unsigned int messageID; unsigned int messageSize; //someData.... }; 

// in main

char* buffer = receiveData(socket); struct msgStructureCommon* msgRCV = (struct msgStructureCommon*)buffer; std::cout<< msgRCV->messageID << std::endl; if(msgRCV->messageID == 911) { struct msgStructureID911* msg911 = (struct msgStructureID911*)buffer; if(msg911->messageSize >= MSG_LIMIT_SIZE_911) { std::cout<< msg911->someData<< std::endl; } else { std::cout<< "ops, message is not correct!" << std::endl; } } else if (msgRCV->messageID == 2013) { //... } 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Could perhaps also post a sample or edit your sample so that I can define the byte position and the size of the struct or so?
Yes, I mean just an example.
you can nest and mix multiple structures too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.