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?

1
  • "P.S for some reason integer 9 is mapped as b'\t\x00\x00\x00' in python ==> what am I missing?" That looks correct to me. What are you expecting? Commented Nov 22, 2019 at 23:27

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.