PHP 读取共享内存二进制数据 (uint32 x = shmop_read(..))


PHP read shared memory binary data (uint32 x = shmop_read(...))

我有一个共享内存区域,我希望在Web服务器中运行的PHP可以访问它。共享内存的布局,其中前 4 个字节是一个 32 位无符号整数,其中包含剩余共享内存区域中有多少字节是有效数据(数据可以是可变大小),即:

Byte Range           Value
------------------   -----------------------------------------------
0 - 3                32-bit unsigned integer - call it numBytes
4 - (numBytes + 4)   char array - The actual data, total of numBytes

如何将前四个字节读取为整数?我唯一能想到的是做一个shmop_read($key, 0, 4)并将返回的字符串值转换为数组,然后将该数组转换为整数,如此处所述。这一切似乎都很混乱,我想知道是否有更清洁的方法可以做到这一点?

我认为这只是一个NVunpack(取决于字节序)。

所以,假设你的$numBytesString看起来像'xff'xff'xff'x7f?然后我会unpack

$numBytesString = shmop_read($key, 0, 4);
$numBytesInt = unpack("V", $numBytesString); // assuming little-endianess
// 2147483647