Search code examples
c++bytememcpymemory-mapped-files

Reading different data types in shared memory


I want to share some memory between different processes running a DLL. Therefore i create a memory-mapped-file by HANDLE hSharedFile = CreateFileMapping(...) then LPBYTE hSharedView = MapViewOfFile(...) and LPBYTE aux = hSharedView

Now I want to read a bool, a int, a float and a char from the aux array. Reading a bool and char is easy. But how would I go around reading a int or float? Notice that the int or float could start at position 9 e.g. a position that is not dividable by 4.

I know you can read a char[4] and then memcpy it into a float or int. But i really need this to be very fast. I am wondering if it is possible to do something with pointers?

Thanks in advance


Solution

  • If you know, for instance, that array elements aux[13..16] contain a float, then you can access this float in several ways:

    float f = *(float*)&aux[13] ;   // Makes a copy. The simplest solution.
    float* pf = (float*)&aux[13] ;  // Here you have to use *pf to access the float.
    float& rf = *(float*)&aux[13] ; // Doesn't make a copy, and is probably what you want.
                                    // (Just use rf to access the float.)