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)
并将返回的字符串值转换为一个数组,然后将该数组转换为一个整数,如 here 所述。这一切看起来很乱,我想知道是否有更简洁的方法来做到这一点?
我认为它只是一个带有 N
或 V
的 unpack
(取决于字节顺序)。
所以,假设您的 $numBytesString 看起来像 \xff\xff\xff\x7f
?那我就unpack
:
$numBytesString = shmop_read($key, 0, 4);
$numBytesInt = unpack("V", $numBytesString); // assuming little-endianess
// 2147483647
我有一个共享内存区域,我想在 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)
并将返回的字符串值转换为一个数组,然后将该数组转换为一个整数,如 here 所述。这一切看起来很乱,我想知道是否有更简洁的方法来做到这一点?
我认为它只是一个带有 N
或 V
的 unpack
(取决于字节顺序)。
所以,假设您的 $numBytesString 看起来像 \xff\xff\xff\x7f
?那我就unpack
:
$numBytesString = shmop_read($key, 0, 4);
$numBytesInt = unpack("V", $numBytesString); // assuming little-endianess
// 2147483647