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?

2
  • 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));? Commented Jul 7, 2016 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. Commented Jul 7, 2016 at 23:50

1 Answer 1

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

2 Comments

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.
Amazing. It was just a wild guess. Glad it worked out :)

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.