Map data in C++ to memory and read data in Python

1

I am mapping integers to memory in C++ (Process 1) and trying to read them in Python (Process 2) ..

Current Results:

1) map integer 3 in C++ ==> Python (b'\x03\x00\x00\x00')

2) map integer 4 in C++ ==> Python (b'\x04\x00\x00\x00'), and so on ..

code:

Process 1

#include <windows.h> 
#include <iostream>

using  namespace std;

void main()
{
    auto name = "new";
    auto size = 4;

    HANDLE hSharedMemory = CreateFileMapping(NULL, NULL, PAGE_READWRITE, NULL, size, name);
    auto pMemory = (int*)MapViewOfFile(hSharedMemory, FILE_MAP_ALL_ACCESS, NULL, NULL, size);

    for (int i = 0; i < 10; i++)
    {
        * pMemory = i;
        cout << i << endl;
        Sleep(1000);
    }

    UnmapViewOfFile(pMemory);
    CloseHandle(hSharedMemory);
}

Process 2

import time
import mmap
bufSize = 4
FILENAME = 'new'

for i in range(10):
    data = mmap.mmap(0, bufSize, tagname=FILENAME, access=mmap.ACCESS_READ)
    dataRead = data.read(bufSize)
    print(dataRead)
    time.sleep(1)

However, my goal is to map an array that is 320*240 in size but when I try a simple array as below

int arr[4] = {1,2,3,4}; and attempt to map to memory by * pMemory = arr;

I am getting the error "a value of type int* cannot be assigned to an entity of type int" and error code "0x80070002" .. Any ideas on how to solve this problem??

P.S for some reason integer 9 is mapped as b'\t\x00\x00\x00' in python ==> what am I missing?

python
c++
memory
asked on Stack Overflow Nov 22, 2019 by Muhamed_Farooq

1 Answer

1

Use memcpy to copy the array to shared memory.

#include <cstring>
#include <windows.h>

int main() {
  int array[320*240];
  const int size = sizeof(array);
  const char *name = "new";

  HANDLE hSharedMemory = CreateFileMapping(NULL, NULL, PAGE_READWRITE, NULL, size, name);
  void *pMemory = MapViewOfFile(hSharedMemory, FILE_MAP_ALL_ACCESS, NULL, NULL, size);

  std::memcpy(pMemory, array, size);

  UnmapViewOfFile(pMemory);
  CloseHandle(hSharedMemory);
}
answered on Stack Overflow Nov 22, 2019 by Indiana Kernick

User contributions licensed under CC BY-SA 3.0