-->

PHP - Access shared Memory created with C++

2019-06-25 22:03发布

问题:

Since a few days i'm trying to get the following thing to work: I have a tiny C++ program which reads some data continuously from a serial port. This data is stored in shared memory like this:

HANDLE hMapFile;
hMapFile = CreateFileMapping(
    INVALID_HANDLE_VALUE,
    NULL,
    PAGE_READWRITE,
    0,
    10,
    NULL);

LPCTSTR pBuf;
pBuf = (LPTSTR) MapViewOfFileEx(
    hMapFile,
    FILE_MAP_ALL_ACCESS,
    0,
    0,
    10,
    NULL);

while(true)
{
    //... some code ...
    CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
    //... some code ...
}

Now i would like to access this shared memory with PHP. so i tried to do the following:

$shm_id = shmop_open($key, $mode, $security, $size);
$read = shmop_read($shm_id, 0, 10);
//... some code ...

But i don't know which key, mode, security and size i should set!

Now, before you gonna write something: I use "MapViewOfFileEx()" because i would like to set a fixed address so PHP can read from a fixed address. I also tried this with "0x00030000" both in C++ and PHP. C++ was able to create the FileMapping, but PHP can't access giving the error-message: shmop_open(): unable to attach or create shared memory segment. As $mode i set "a" for only read-permissions. As $security i set 0777 for all-access... As $size i set 10 byte.

As written in the PHP-manual they say i should set 0 for $security AND $size, if i'm trying to attach to a existing shared-memory, but this is also not working.

How can i get this concept done? I guess that the BaseAdress of C++ is not the same like the $key in PHP, but how can i tell PHP then where the shared-memory block is? If this is impossible to get this working: Would there be another way to transmit data from a C++ program to PHP (running on wamp-server)?

PS: as i recently read in other questions, it seems to be impossible to communicate with shared-memory... I never worked with named-pipes before, but how would my problem be realized using named-pipes? Or is there a better/faster way to enable communication between C++ and PHP?

回答1:

I'd recommend you to use Redis to deal with the communications between C++ and PHP. You can use his Pub /sub module, is very powerfull. http://redis.io/topics/pubsub. Here you have a list of clients for redis: http://redis.io/clients