carcassonne has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

What approaches can be used in Perl for receiving/sending data to a server written in C that expects said data to be exactly delimited according to C types ? Like:

struct Result { DWORD var1; BYTE var2; WORD var3; short var4; int var5; float var6; };

The server expects the exact data lengths for each variable because it simply 'shifts' the bytes as they come in into its appropriate structures.

Are there recipes to shape Perl internal data representation to fit C structures before sending them in the network ?

Same for receiving C data: Are there recipes to read in C data and use Perl hashes based on the C structure definition ?

Is there a Perl module (or modules) that can help ?

Thanks !

Replies are listed 'Best First'.
Re: Working with C structures over network
by Corion (Patriarch) on Jan 30, 2006 at 20:21 UTC

    Depending on the kind of data you have available and the number of structures, C compilers and records you have to wrap, there are two approaches:

    The simple approach is to use the pack and unpack functions, which pack an array into a string and back.

    Your example struct would likely be packed as:

    pack "lCvsif", $var1, $var2, $var3, $var4, $var5, $var6;

    With the caveat that floating point structures are only valid for passing around on the same architecture, as there is no standard.

    The hard, but potentially more rewarding approach is Convert::Binary::C, which takes a C struct definition and a C compiler, and packs an array into a string that looks as if the C compiler did it. This most likely is overkill.

Re: Working with C structures over network
by explorer (Chaplain) on Jan 30, 2006 at 20:19 UTC
Re: Working with C structures over network
by BrowserUk (Patriarch) on Jan 30, 2006 at 21:11 UTC

    Be careful of alignment issues. Especially where you have non-byte members following single bytes within a struct. C compilers will often add padding to place WORD and DWORD members on 2 or 4 byte boundaries for efficiency reasons.

    To quote K&R (page 130 in my copy).

    But don't assume that the size of a struct is the sum of the size of it's members--because of alignment requirements for different objects, there may be "holes" in the structure.

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Working with C structures over network
by ikegami (Patriarch) on Jan 30, 2006 at 20:27 UTC