Re: packing a C structure
- From: "jl_post@xxxxxxxxxxx" <jl_post@xxxxxxxxxxx>
- Date: Fri, 26 Oct 2007 10:37:05 -0700
On Oct 25, 10:57 pm, haai...@xxxxxxxxx wrote:
hi ,,,
iam trying to pack a C structure to send via socket..i would like to
know how to frame the template for the C structure..
this is my structure
typedef struct buffer_t {
uint32_t a;
char b[16];
uint32_t c;
uint32_t d;
char e[6];
char f[8];
} buffer_t;
kindly suggest me the format for the pack function call..this will
help me to solve my issue...
Hi,
I have the impression that what you want is to pack values in Perl
into a binary string of data that matches how a C program would do it.
If I'm right, this might work:
my $stringToSend = pack('I c16 I I c6 c8',
<YOUR PERL VARIABLES GO HERE>);
However, it's quite likely that the C program packs the data in a
way so that they are properly byte-aligned. If that's the case, the
above pack string may not work, and you'd probably have better luck
with the following pack string that inserts padding in the proper
places:
my $stringToSend = pack('I c16 x![I] I I c6 c8 x![I]',
<YOUR PERL VARIABLES GO HERE>);
Out of curiosity, when you declare b as a char array of 16 elements
is that because you're sending over 16 separate char values, or are
you sending one null-terminated string that can be a maximum of 15
characters long?
If your intention is to use b[16] as a single string (holding a
maximum of 15 characters), you probably want to replace "c16" in the
above pack strings to "Z16" (you may also want to replace "c6" and
"c8" with "Z6" and "Z8"). That way, instead of sending over 33
separate variables (that is, three ints plus 30 characters), you'd be
sending over six separate variables (that is, three ints plus three
strings).
So if it's the case that you want to send over three ints and three
strings, you might use code like this:
my $a = 1;
my $b = "Title of book";
my $c = 3;
my $d = 4;
my $e = "March";
my $f = "Sunday";
my $stringToSend = pack('I Z16 x![I] I I Z6 Z8 x![I]',
$a, $b, $c, $d, $e, $f);
Unfortunately, there's no real way to know what the proper pack
string should be unless you analyze the binary structure that your C
program writes out (or if can find one, reads in). But it's likely
that one of pack strings I gave you (or a variant) will work.
I hope this helps. Perl's pack() function is very powerful and
useful when dealing with C structures written out to disk.
-- Jean-Luc
.
- Follow-Ups:
- Re: packing a C structure
- From: rams
- Re: packing a C structure
- References:
- packing a C structure
- From: haairam
- packing a C structure
- Prev by Date: Re: PID of exec
- Next by Date: Re: PID of exec
- Previous by thread: Re: packing a C structure
- Next by thread: Re: packing a C structure
- Index(es):
Relevant Pages
|