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

I would like to pack() the equivalent of a Microsoft DATA_BLOB structure, which looks like this:
typedef struct DATA_BLOB { DWORD cbData; // DWORD that contains the count, in bytes, of data. BYTE *pbData; // Pointer to the data buffer. }
According to MSDN, a DWORD is a 32-bit unsigned long. So, in terms of pack(), I assume a DWORD corresponds to 'L'. The second member of the structure, a BYTE pointer to the data, seems a little more tricky. Since it needs a pointer to the data, I assume pack() is going to expect 'P', but I think a BYTE is 'C', so maybe some double packing is required? Here's what I've come up with...how far off am I?

my $data_blob = pack('LC', length($data), pack('P', $data));

Replies are listed 'Best First'.
Re: pack() Question - DATA_BLOB structure
by Anonymous Monk on Jul 08, 2009 at 03:43 UTC

    You've got it backwards. You need a byte in a pointer (pointer to a byte) not a pointer in a byte (which probably won't work on machines from the last couple of decades).

    A string is already a sequence of bytes (ignoring stuff like unicode, etc), so theres no need to pack it as such.

    Untested correction code:

    my $blob = pack('LP', length($data), $data);

    There are a lot of issues dealing with packing/unpacking C structs. For details on these and ways around them, please see:

Re: pack() Question - DATA_BLOB structure
by jbt (Chaplain) on Jul 08, 2009 at 03:47 UTC
    Looks like a 32 bit unsigned integer followed by a pointer to an fixed length string. What about the following line of code?
    my $data_blob = pack("LP", $data);