Search code examples
phpcstructpack

Packing C structs from PHP


I've played around with pack() for longer than I'd like to admit, and accidentally stumbled across data structure alignment. Is there a "good" way to create C structures from within PHP and account for these extra padding bytes?

I know that you can use "x" to inject NULL bytes, but how do you determine where these go and how many to use programmatically?

Along the same lines, which of these methods is better for modeling a char foo[10] array?

$struct = pack('a9x', $string);
// vs.
$struct = pack('a10', substr($string, 0, 9));

I believe they both accomplish the same thing, but I'm not sure of any potential pitfalls.


Solution

  • What you try to do is achievable, but highly dangerous. Let me explain:

    • PHP code is largely independant from the Hardware/OS/C runtime it runs on
    • (Portable) C source code mostly is also
    • The compilation/linking/loading process of a C binary definitly is not (especially if you leave the padding/packing issues to the compiler)

    Now what you try to do in PHP is a partial reimplementation of exactly this compilation/linking/loading process, but without a reliable mechanism to determine to adapt to the environment.

    I recommend one of two IMHO more reliable ways to do this:

    • Write a PHP extension (this is rather easy), that does the structure-dependant stuff for you, including the headers from your C program. If you compile this on the target system (or one with an equal environment) you will not run into the troubles above
    • Chose another, higher level mechanism to communicate: We have successfully used SysV messages for a very similar requirement, but there are plenty of ways to go.