1

I have a shared memory region which I to want access with PHP running in a web server. The shared memory is laid out where the first 4 bytes is a 32-bit unsigned integer which contains how many bytes are valid data within the remaining shared memory region (the data can be variable size), i.e.:

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

How do I read in the first four bytes as an integer? The only thing I can think of is do a shmop_read($key, 0, 4) and convert the returned string value to an array, then convert that array to an integer as described here. This all seems very messy and I was wondering if there is a cleaner way to do this?

Community
  • 1
  • 1
user2205930
  • 1,046
  • 12
  • 26
  • 1
    Maybe it's just an `unpack("V", shmop_read($key, 0, 4));`. But could you post a `var_dump(shmop_read($key, 0, 4));`? – Jens A. Koch Jul 07 '16 at 23:35
  • 1
    After looking at `unpack()` I think your answer is correct. I will not be able to test it for a day or so; unfortunately. Could you give your comment as an answer because I cannot mark a comment as an answer. – user2205930 Jul 07 '16 at 23:50

1 Answers1

1

I think it's just an unpack with N or V (depending on endianness).

So, assuming your $numBytesString looks like \xff\xff\xff\x7f? Then i would unpack:

$numBytesString = shmop_read($key, 0, 4);

$numBytesInt = unpack("V", $numBytesString); // assuming little-endianess

// 2147483647
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
  • Thank you! This worked perfectly. The only thing I needed to add was `$numBytesInt = (integer) $numBytesInt[1];` because `unpack` returns an array. Although, I'm new to PHP so that last bit may not be needed. – user2205930 Jul 09 '16 at 00:21
  • Amazing. It was just a wild guess. Glad it worked out :) – Jens A. Koch Jul 09 '16 at 00:53