home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / C.pm < prev    next >
Encoding:
Perl POD Document  |  2003-09-16  |  90.7 KB  |  3,261 lines

  1. ################################################################################
  2. #
  3. # MODULE: Convert::Binary::C
  4. #
  5. ################################################################################
  6. #
  7. # DESCRIPTION: Convert::Binary::C Perl extension module
  8. #
  9. ################################################################################
  10. #
  11. # $Project: /Convert-Binary-C $
  12. # $Author: joker $
  13. # $Date: 2003/09/16 18:16:40 $
  14. # $Revision: 1.2 $
  15. # $Snapshot: /Convert-Binary-C/0.40 $
  16. # $Source: /srv/cvs/tsw/WEB/Apache2/perl/site/lib/Convert/Binary/C.pm,v $
  17. #
  18. ################################################################################
  19. #
  20. # Copyright (c) 2002-2003 Marcus Holland-Moritz. All rights reserved.
  21. # This program is free software; you can redistribute it and/or modify
  22. # it under the same terms as Perl itself.
  23. #
  24. ################################################################################
  25.  
  26. package Convert::Binary::C;
  27.  
  28. use strict;
  29. use DynaLoader;
  30. use Carp;
  31. use vars qw( @ISA $VERSION $XS_VERSION $AUTOLOAD );
  32.  
  33. @ISA = qw(DynaLoader);
  34.  
  35. $VERSION = do { my @r = '$Snapshot: /Convert-Binary-C/0.40 $' =~ /(\d+\.\d+(?:_\d+)?)/; @r ? $r[0] : '9.99' };
  36.  
  37. bootstrap Convert::Binary::C $VERSION;
  38.  
  39. # Unfortunately, XS AUTOLOAD isn't supported
  40. # by stable perl distributions before 5.8.0.
  41.  
  42. sub AUTOLOAD
  43. {
  44.   my $self = shift;
  45.   my $opt = $AUTOLOAD;
  46.   ref $self or croak "$self is not an object";
  47.   $opt =~ s/.*://;
  48.   $opt =~ /^[A-Z]/ or croak "Invalid method $opt called";
  49.   @_ <= 1 or croak "$opt cannot take more than one argument";
  50.   unless( @_ or defined wantarray ) {
  51.     carp "Useless use of $opt in void context";
  52.     return;
  53.   }
  54.   $opt = eval { $self->configure( $opt, @_ ) };
  55.   $@ =~ s/\s+at.*?C\.pm.*//s, croak $@ if $@;
  56.   $opt;
  57. }
  58.  
  59. 1;
  60.  
  61. __END__
  62.  
  63. =head1 NAME
  64.  
  65. Convert::Binary::C - Binary Data Conversion using C Types
  66.  
  67. =head1 SYNOPSIS
  68.  
  69. =head2 Simple
  70.  
  71.   use Convert::Binary::C;
  72.   
  73.   #---------------------------------------------
  74.   # Create a new object and parse embedded code
  75.   #---------------------------------------------
  76.   my $c = Convert::Binary::C->new->parse( <<ENDC );
  77.   
  78.   enum Month { JAN, FEB, MAR, APR, MAY, JUN,
  79.                JUL, AUG, SEP, OCT, NOV, DEC };
  80.   
  81.   struct Date {
  82.     int        year;
  83.     enum Month month;
  84.     int        day;
  85.   };
  86.   
  87.   ENDC
  88.   
  89.   #-----------------------------------------------
  90.   # Pack Perl data structure into a binary string
  91.   #-----------------------------------------------
  92.   my $date = { year => 2002, month => 'DEC', day => 24 };
  93.   
  94.   my $packed = $c->pack( 'Date', $date );
  95.  
  96. =head2 Advanced
  97.  
  98.   use Convert::Binary::C;
  99.   use Data::Dumper;
  100.   
  101.   #---------------------
  102.   # Create a new object
  103.   #---------------------
  104.   my $c = new Convert::Binary::C ByteOrder => 'BigEndian';
  105.   
  106.   #---------------------------------------------------
  107.   # Add include paths and global preprocessor defines
  108.   #---------------------------------------------------
  109.   $c->Include( '/usr/lib/gcc-lib/i686-pc-linux-gnu/3.2.2/include',
  110.                '/usr/include' )
  111.     ->Define( qw( __USE_POSIX __USE_ISOC99=1 ) );
  112.   
  113.   #----------------------------------
  114.   # Parse the 'time.h' header file
  115.   #----------------------------------
  116.   $c->parse_file( 'time.h' );
  117.   
  118.   #---------------------------------------
  119.   # See which files the object depends on
  120.   #---------------------------------------
  121.   print Dumper( [keys %{$c->dependencies}] );
  122.   
  123.   #-----------------------------------------------------------
  124.   # See if struct timespec is defined and dump its definition
  125.   #-----------------------------------------------------------
  126.   if( $c->def( 'struct timespec' ) ) {
  127.     print Dumper( $c->struct( 'timespec' ) );
  128.   }
  129.   
  130.   #-------------------------------
  131.   # Create some binary dummy data
  132.   #-------------------------------
  133.   my $data = "binaryteststring";
  134.   
  135.   #--------------------------------------------------------
  136.   # Unpack $data according to 'struct timespec' definition
  137.   #--------------------------------------------------------
  138.   if( length($data) >= $c->sizeof( 'timespec' ) ) {
  139.     my $perl = $c->unpack( 'timespec', $data );
  140.     print Dumper( $perl );
  141.   }
  142.   
  143.   #--------------------------------------------------------
  144.   # See which member lies at offset 5 of 'struct timespec'
  145.   #--------------------------------------------------------
  146.   my $member = $c->member( 'timespec', 5 );
  147.   print "member( 'timespec', 5 ) = '$member'\n";
  148.  
  149. =head1 DESCRIPTION
  150.  
  151. Convert::Binary::C is a preprocessor and parser for C type
  152. definitions. It is highly configurable and should support
  153. arbitrarily complex data structures. Its object-oriented
  154. interface has L<C<pack>|/"pack"> and L<C<unpack>|/"unpack"> methods
  155. that act as replacements for
  156. Perl's L<C<pack>|perlfunc/"pack"> and L<C<unpack>|perlfunc/"unpack"> and
  157. allow to use the C types instead of a string representation
  158. of the data structure for conversion of binary data from and
  159. to Perl's complex data structures.
  160.  
  161. Actually, what Convert::Binary::C does is not very different
  162. from what a C compiler does, just that it doesn't compile the
  163. source code into an object file or executable, but only parses
  164. the code and allows Perl to use the enumerations, structs, unions
  165. and typedefs that have been defined within your C source for binary
  166. data conversion, similar to
  167. Perl's L<C<pack>|perlfunc/"pack"> and L<C<unpack>|perlfunc/"unpack">.
  168.  
  169. Beyond that, the module offers a lot of convenience methods
  170. to retrieve information about the C types that have been parsed.
  171.  
  172. =head2 Background and History
  173.  
  174. In late 2000 I wrote a realtime debugging interface for an
  175. embedded medical device that allowed me to send out data from
  176. that device over its integrated ethernet adapter.
  177. The interface was C<printf()>-like, so you could easily send
  178. out strings or numbers. But you could also send out what I
  179. called I<arbitrary data>, which was intended for arbitrary
  180. blocks of the device's memory.
  181.  
  182. Another part of this realtime debugger was a Perl application
  183. running on my workstation that gathered all the messages that
  184. were sent out from the embedded device. It printed all the
  185. strings an numbers, and hexdumped the arbitrary data.
  186. However, manually parsing a couple of 300 byte hexdumps of a
  187. complex C structure is not only frustrating, but also error-prone
  188. and time consuming.
  189.  
  190. Using L<C<unpack>|perlfunc/"unpack"> to retrieve the contents
  191. of a C structure works fine for small structures and if you
  192. don't have to deal with struct member alignment. But otherwise,
  193. maintaining such code can be as awful as deciphering hexdumps.
  194.  
  195. As I didn't find anything to solve my problem on the CPAN,
  196. I wrote a little module that translated simple C structs
  197. into L<C<unpack>|perlfunc/"unpack"> strings. It worked, but
  198. it was slow. And since it couldn't deal with struct member
  199. alignment, I soon found myself adding padding bytes everywhere.
  200. So again, I had to maintain two sources, and changing one of
  201. them forced me to touch the other one.
  202.  
  203. All in all, this little module seemed to make my task a bit
  204. easier, but it was far from being what I was thinking of:
  205.  
  206. =over 2
  207.  
  208. =item *
  209.  
  210. A module that could directly use the source I've been coding
  211. for the embedded device without any modifications.
  212.  
  213. =item *
  214.  
  215. A module that could be configured to match the properties
  216. of the different compilers and target platforms I was using.
  217.  
  218. =item *
  219.  
  220. A module that was fast enough to decode a great amount of
  221. binary data even on my slow workstation.
  222.  
  223. =back
  224.  
  225. I didn't know how to accomplish these tasks until I read something
  226. about XS. At least, it seemed as if it could solve my performance
  227. problems. However, writing a C parser in C isn't easier than it is
  228. in Perl. But writing a C preprocessor from scratch is even worse.
  229.  
  230. Fortunately enough, after a few weeks of searching I found both,
  231. a lean, open-source C preprocessor library, and a reusable YACC
  232. grammar for ANSI-C. That was the beginning of the development of
  233. Convert::Binary::C in late 2001.
  234.  
  235. Now, I'm successfully using the module in my embedded environment
  236. since long before it appeared on CPAN. From my point of view, it
  237. is exactly what I had in mind. It's fast, flexible, easy to use
  238. and portable. It doesn't require external programs or other Perl
  239. modules.
  240.  
  241. =head2 About this document
  242.  
  243. This document describes how to use Convert::Binary::C. A lot of
  244. different features are presented, and the example code sometimes
  245. uses Perl's more advanced language elements. If your experience
  246. with Perl is rather limited, you should know how to use Perl's
  247. very good documentation system.
  248.  
  249. To look up one of the manpages, use the L<C<perldoc>|perldoc> command.
  250. For example,
  251.  
  252.   perldoc perl
  253.  
  254. will show you Perl's main manpage. To look up a specific Perl
  255. function, use C<perldoc -f>:
  256.  
  257.   perldoc -f map
  258.  
  259. gives you more information about the L<C<map>|perlfunc/"map"> function.
  260. You can also search the FAQ using C<perldoc -q>:
  261.  
  262.   perldoc -q array
  263.  
  264. will give you everything you ever wanted to know about Perl
  265. arrays. But now, let's go on with some real stuff!
  266.  
  267. =head2 Why use Convert::Binary::C?
  268.  
  269. Say you want to pack (or unpack) data according to the following
  270. C structure:
  271.  
  272.   struct foo {
  273.     char ary[3];
  274.     unsigned short baz;
  275.     int bar;
  276.   };
  277.  
  278. You could of course use
  279. Perl's L<C<pack>|perlfunc/"pack"> and L<C<unpack>|perlfunc/"unpack"> functions:
  280.  
  281.   @ary = (1, 2, 3);
  282.   $baz = 40000;
  283.   $bar = -4711;
  284.   $binary = pack 'c3 S i', @ary, $baz, $bar;
  285.  
  286. But this implies that the struct members are byte aligned. If
  287. they were long aligned (which is the default for most compilers),
  288. you'd have to write
  289.  
  290.   $binary = pack 'c3 x S x2 i', @ary, $baz, $bar;
  291.  
  292. which doesn't really increase readability.
  293.  
  294. Now imagine that you need to pack the data for a completely
  295. different architecture with different byte order. You would
  296. look into the L<C<pack>|perlfunc/"pack"> manpage again and
  297. perhaps come up with this:
  298.  
  299.   $binary = pack 'c3 x n x2 N', @ary, $baz, $bar;
  300.  
  301. However, if you try to unpack C<$foo> again, your signed values
  302. have turned into unsigned ones.
  303.  
  304. All this can still be managed with Perl. But imagine your
  305. structures get more complex? Imagine you need to support
  306. different platforms? Imagine you need to make changes to
  307. the structures? You'll not only have to change the C source
  308. but also dozens of L<C<pack>|perlfunc/"pack"> strings in
  309. your Perl code. This is no fun. And Perl should be fun.
  310.  
  311. Now, wouldn't it be great if you could just read in the C
  312. source you've already written and use all the types defined
  313. there for packing and unpacking? That's what Convert::Binary::C
  314. does.
  315.  
  316. =head2 Creating a Convert::Binary::C object
  317.  
  318. To use Convert::Binary::C just say
  319.  
  320.   use Convert::Binary::C;
  321.  
  322. to load the module. Its interface is completely object
  323. oriented, so it doesn't export any functions.
  324.  
  325. Next, you need to create a new Convert::Binary::C object. This
  326. can be done by either
  327.  
  328.   $c = Convert::Binary::C->new;
  329.  
  330. or
  331.  
  332.   $c = new Convert::Binary::C;
  333.  
  334. You can optionally pass configuration options to
  335. the L<constructor|/"new"> as described in the next section.
  336.  
  337. =head2 Configuring the object
  338.  
  339. To configure a Convert::Binary::C object, you can either call
  340. the L<C<configure>|/"configure"> method or directly pass the configuration
  341. options to the L<constructor|/"new">. If you want to change byte order
  342. and alignment, you can use
  343.  
  344.   $c->configure( ByteOrder => 'LittleEndian',
  345.                  Alignment => 2 );
  346.  
  347. or you can change the construction code to
  348.  
  349.   $c = new Convert::Binary::C ByteOrder => 'LittleEndian',
  350.                               Alignment => 2;
  351.  
  352. Either way, the object will now know that it should use
  353. little endian (Intel) byte order and 2-byte struct member
  354. alignment for packing and unpacking.
  355.  
  356. Alternatively, you can use the option names as names of
  357. methods to configure the object, like:
  358.  
  359.   $c->ByteOrder( 'LittleEndian' );
  360.  
  361. You can also retrieve information about the current
  362. configuration of a Convert::Binary::C object. For details,
  363. see the section about the L<C<configure>|/"configure"> method.
  364.  
  365. =head2 Parsing C code
  366.  
  367. Convert::Binary::C allows two ways of parsing C source. Either
  368. by parsing external C header or C source files:
  369.  
  370.   $c->parse_file( 'header.h' );
  371.  
  372. Or by parsing C code embedded in your script:
  373.  
  374.   $c->parse( <<'CCODE' );
  375.   struct foo {
  376.     char ary[3];
  377.     unsigned short baz;
  378.     int bar;
  379.   };
  380.   CCODE
  381.  
  382. Now the object C<$c> will know everything about C<struct foo>.
  383. The example above uses a so-called here-document. It allows to
  384. easily embed multiline strings in your code. You can find more
  385. about here-documents in L<perldata> or L<perlop>.
  386.  
  387. Since the L<C<parse>|/"parse"> and L<C<parse_file>|/"parse_file"> methods
  388. throw an exception when a parse error occurs, you usually want to catch
  389. these in an C<eval> block:
  390.  
  391.   eval { $c->parse_file('header.h') };
  392.   if( $@ ) {
  393.     # do something appropriate
  394.   }
  395.  
  396. Perl's special C<$@> variable will contain an empty string (which
  397. evaluates to a false value in boolean context) on success or
  398. an error string on failure.
  399.  
  400. As another feature, L<C<parse>|/"parse"> and L<C<parse_file>|/"parse_file"> return
  401. a reference to their object on success, just like L<C<configure>|/"configure"> does
  402. when you're configuring the object. This will allow you to write constructs
  403. like this:
  404.  
  405.   my $c = eval {
  406.     Convert::Binary::C->new( Include => ['/usr/include'] )
  407.                       ->parse_file( 'header.h' )
  408.   };
  409.   if( $@ ) {
  410.     # do something appropriate
  411.   }
  412.  
  413. =head2 Packing and unpacking
  414.  
  415. Convert::Binary::C has two methods, L<C<pack>|/"pack"> and L<C<unpack>|/"unpack">,
  416. that act similar to the functions of same denominator in Perl.
  417. To perform the packing described in the example above,
  418. you could write:
  419.  
  420.   $data = {
  421.     ary => [1, 2, 3],
  422.     baz => 40000,
  423.     bar => -4711,
  424.   };
  425.   $binary = $c->pack( 'foo', $data );
  426.  
  427. Unpacking will work exactly the same way, just that
  428. the L<C<unpack>|/"unpack"> method will take a byte string as its input
  429. and will return a reference to a (possibly very complex)
  430. Perl data structure.
  431.  
  432.   $binary = from_memory();
  433.   $data = $c->unpack( 'foo', $binary );
  434.  
  435. You can now easily access all of the values:
  436.  
  437.   print "foo.ary[1] = $data->{ary}[1]\n";
  438.  
  439. Or you can even more conveniently use
  440. the L<Data::Dumper|Data::Dumper> module:
  441.  
  442.   use Data::Dumper;
  443.   print Dumper( $data );
  444.  
  445. The output would look something like this:
  446.  
  447.   $VAR1 = {
  448.     'bar' => -271,
  449.     'baz' => 5000,
  450.     'ary' => [
  451.       42,
  452.       48,
  453.       100
  454.     ]
  455.   };
  456.  
  457. =head2 Preprocessor configuration
  458.  
  459. Convert::Binary::C uses Thomas Pornin's C<ucpp> as an internal
  460. C preprocessor. It is compliant to ISO-C99, so you don't have
  461. to worry about using even weird preprocessor constructs in
  462. your code.
  463.  
  464. If your C source contains includes or depends upon preprocessor
  465. defines, you may need to configure the internal preprocessor.
  466. Use the C<Include> and C<Define> configuration options for that:
  467.  
  468.   $c->configure( Include => ['/usr/include',
  469.                              '/home/mhx/include'],
  470.                  Define  => [qw( NDEBUG FOO=42 )] );
  471.  
  472. If your code uses system includes, it is most likely
  473. that you will need to define the symbols that are usually
  474. defined by the compiler.
  475.  
  476. On some operating systems, the system includes require the
  477. preprocessor to predefine a certain set of assertions.
  478. Assertions are supported by C<ucpp>, and you can define them
  479. either in the source code using C<#assert> or as a property
  480. of the Convert::Binary::C object using C<Assert>:
  481.  
  482.   $c->configure( Assert => ['predicate(answer)'] );
  483.  
  484. =head2 Supported pragma directives
  485.  
  486. Convert::Binary::C supports the C<pack> pragma to locally override
  487. struct member alignment. The supported syntax is as follows:
  488.  
  489. =over 4
  490.  
  491. =item #pragma pack( ALIGN )
  492.  
  493. Sets the new alignment to ALIGN.
  494.  
  495. =item #pragma pack
  496.  
  497. Resets the alignment to its original value.
  498.  
  499. =item #pragma pack( push, ALIGN )
  500.  
  501. Saves the current alignment on a stack and sets the new
  502. alignment to ALIGN.
  503.  
  504. =item #pragma pack( pop )
  505.  
  506. Restores the alignment to the last value saved on the
  507. stack.
  508.  
  509. =back
  510.  
  511.   /*  Example assumes sizeof( short ) == 2, sizeof( long ) == 4.  */
  512.   
  513.   #pragma pack(1)
  514.   
  515.   struct nopad {
  516.     char a;               /* no padding bytes between 'a' and 'b' */
  517.     long b;
  518.   };
  519.   
  520.   #pragma pack            /* reset to "native" alignment          */
  521.   
  522.   #pragma pack( push, 2 )
  523.   
  524.   struct pad {
  525.     char    a;            /* one padding byte between 'a' and 'b' */
  526.     long    b;
  527.   
  528.   #pragma pack( push, 1 )
  529.   
  530.     struct {
  531.       char  c;            /* no padding between 'c' and 'd'       */
  532.       short d;
  533.     }       e;            /* sizeof( e ) == 3                     */
  534.   
  535.   #pragma pack( pop );    /* back to pack( 2 )                    */
  536.   
  537.     long    f;            /* one padding byte between 'e' and 'f' */
  538.   };
  539.   
  540.   #pragma pack( pop );    /* back to "native"                     */
  541.  
  542. The C<pack> pragma as it is currently implemented only affects
  543. the I<maximum> struct member alignment. There are compilers
  544. that also allow to specify the I<minimum> struct member
  545. alignment. This is not supported by Convert::Binary::C.
  546.  
  547. =head2 Automatic configuration using C<ccconfig>
  548.  
  549. As there are over 20 different configuration options, setting
  550. all of them correctly can be a lengthy and tedious task.
  551.  
  552. The L<C<ccconfig>|ccconfig> script, which is bundled with this
  553. module, aims at automatically determining the correct compiler
  554. configuration by testing the compiler executable. It works for
  555. both, native and cross compilers.
  556.  
  557. =head1 UNDERSTANDING TYPES
  558.  
  559. This section covers one of the fundamental features of
  560. Convert::Binary::C. It's how I<type expressions>, referred to
  561. as TYPEs in the L<method reference|/"METHODS">, are handled
  562. by the module.
  563.  
  564. Many of the methods,
  565. namely L<C<pack>|/"pack">, L<C<unpack>|/"unpack">, L<C<sizeof>|/"sizeof">, L<C<typeof>|/"typeof">, L<C<member>|/"member"> and L<C<offsetof>|/"offsetof">,
  566. are passed a TYPE to operate on as their first argument.
  567.  
  568. =head2 Standard Types
  569.  
  570. These are trivial. Standard types are simply enum names, struct
  571. names, union names, or typedefs. Almost every method that wants
  572. a TYPE will accept a standard type.
  573.  
  574. For enums, structs and unions, the prefixes C<enum>, C<struct> and C<union> are
  575. optional. However, if a typedef with the same name exists, like in
  576.  
  577.   struct foo {
  578.     int bar;
  579.   };
  580.   
  581.   typedef int foo;
  582.  
  583. you will have to use the prefix to distinguish between the
  584. struct and the typedef. Otherwise, a typedef is always given
  585. preference.
  586.  
  587. =head2 Basic Types
  588.  
  589. Basic types, or atomic types, are C<int> or C<char>, for example.
  590. It's possible to use these basic types without having parsed any
  591. code. You can simply do
  592.  
  593.   $c = new Convert::Binary::C;
  594.   $size = $c->sizeof( 'unsigned long' );
  595.   $data = $c->pack( 'short int', 42 );
  596.  
  597. Even though the above works fine, it is not possible to define
  598. more complex types on the fly, so
  599.  
  600.   $size = $c->sizeof( 'struct { int a, b; }' );
  601.  
  602. will result in an error.
  603.  
  604. Basic types are not supported by all methods. For example, it makes
  605. no sense to use L<C<member>|/"member"> or L<C<offsetof>|/"offsetof"> on
  606. a basic type. Using L<C<typeof>|/"typeof"> isn't very useful, but
  607. supported.
  608.  
  609. =head2 Member Expressions
  610.  
  611. This is by far the most complex part, depending on the complexity of
  612. your data structures. Any L<standard type|/"Standard Types"> that
  613. defines a compound or an array may be followed by a member expression
  614. to select only a certain part of the data type. Say you have parsed the
  615. following C code:
  616.  
  617.   struct foo {
  618.     long type;
  619.     struct {
  620.       short x, y;
  621.     } array[20];
  622.   };
  623.   
  624.   typedef struct foo matrix[8][8];
  625.  
  626. You may want to know the size of the C<array> member of C<struct foo>.
  627. This is quite easy:
  628.  
  629.   print $c->sizeof( 'foo.array' ), " bytes";
  630.  
  631. will print
  632.  
  633.   80 bytes
  634.  
  635. depending of course on the C<ShortSize> you configured.
  636.  
  637. If you wanted to unpack only a single column of C<matrix>, that's
  638. easy as well (and of course it doesn't matter which index you use):
  639.  
  640.   $column = $c->unpack( 'matrix[2]', $data );
  641.  
  642. Member expressions can be arbitrarily complex:
  643.  
  644.   $type = $c->typeof( 'matrix[2][3].array[7].y' );
  645.   print "the type is $type";
  646.  
  647. will, for example, print
  648.  
  649.   the type is short
  650.  
  651. Member expressions are also used as the second argument
  652. to L<C<offsetof>|/"offsetof">.
  653.  
  654. =head2 Offsets
  655.  
  656. Members returned by the L<C<member>|/"member"> method have an optional
  657. offset suffix to indicate that the given offset doesn't point to the
  658. start of that member. For example,
  659.  
  660.   $member = $c->member( 'matrix', 1431 );
  661.   print $member;
  662.  
  663. will print
  664.  
  665.   [2][1].type+3
  666.  
  667. If you would use this as a member expression, like in
  668.  
  669.   $size = $c->sizeof( "matrix $member" );
  670.  
  671. the offset suffix will simply be ignored. Actually, it will be
  672. ignored for all methods if it's used in the first argument.
  673.  
  674. When used in the second argument to L<C<offsetof>|/"offsetof">,
  675. it will usually do what you mean, i. e. the offset suffix, if
  676. present, will be considered when determining the offset. This
  677. behaviour ensures that
  678.  
  679.   $member = $c->member( 'foo', 43 );
  680.   $offset = $c->offsetof( 'foo', $member );
  681.   print "'$member' is located at offset $offset of struct foo";
  682.  
  683. will always correctly set C<$offset>:
  684.  
  685.   '.array[9].y+1' is located at offset 43 of struct foo
  686.  
  687. If this is not what you mean, e. g. because you want to know the
  688. offset where the member returned by L<C<member>|/"member"> starts,
  689. you just have to remove the suffix:
  690.  
  691.   $member =~ s/\+\d+$//;
  692.   $offset = $c->offsetof( 'foo', $member );
  693.   print "'$member' is starts at offset $offset of struct foo";
  694.  
  695. This would then print:
  696.  
  697.   '.array[9].y' is starts at offset 42 of struct foo
  698.  
  699. =head1 METHODS
  700.  
  701. =head2 new
  702.  
  703. =over 8
  704.  
  705. =item C<new>
  706.  
  707. =item C<new> OPTION1 =E<gt> VALUE1, OPTION2 =E<gt> VALUE2, ...
  708.  
  709. The constructor is used to create a new Convert::Binary::C object.
  710. You can simply use
  711.  
  712.   $c = new Convert::Binary::C;
  713.  
  714. without additional arguments to create an object, or you can
  715. optionally pass any arguments to the constructor that are
  716. described for the L<C<configure>|/"configure"> method.
  717.  
  718. =back
  719.  
  720. =head2 configure
  721.  
  722. =over 8
  723.  
  724. =item C<configure>
  725.  
  726. =item C<configure> OPTION
  727.  
  728. =item C<configure> OPTION1 =E<gt> VALUE1, OPTION2 =E<gt> VALUE2, ...
  729.  
  730. This method can be used to configure an existing Convert::Binary::C
  731. object or to retrieve its current configuration.
  732.  
  733. To configure the object, the list of options consists of key
  734. and value pairs and must therefore contain an even number of
  735. elements. L<C<configure>|/"configure"> (and also L<C<new>|/"new"> if
  736. used with configuration options) will throw an exception if you
  737. pass an odd number of elements. Configuration will normally look
  738. like this:
  739.  
  740.   $c->configure( ByteOrder => 'BigEndian', IntSize => 2 );
  741.  
  742. To retrieve the current value of a configuration option, you
  743. must pass a single argument to L<C<configure>|/"configure"> that
  744. holds the name of the option, just like
  745.  
  746.   $order = $c->configure( 'ByteOrder' );
  747.  
  748. If you want to get the values of all configuration options at
  749. once, you can call L<C<configure>|/"configure"> without any
  750. arguments and it will return a reference to a hash table that
  751. holds the whole object configuration. This can be conveniently
  752. used with the L<Data::Dumper|Data::Dumper> module, for example:
  753.  
  754.   use Convert::Binary::C;
  755.   use Data::Dumper;
  756.   
  757.   $c = new Convert::Binary::C Define  => ['DEBUGGING', 'FOO=123'],
  758.                               Include => ['/usr/include'];
  759.   
  760.   print Dumper( $c->configure );
  761.  
  762. This will print something like this:
  763.  
  764.   $VAR1 = {
  765.     'Define' => [
  766.       'DEBUGGING',
  767.       'FOO=123'
  768.     ],
  769.     'ByteOrder' => 'LittleEndian',
  770.     'LongSize' => 4,
  771.     'IntSize' => 4,
  772.     'ShortSize' => 2,
  773.     'HasMacroVAARGS' => 1,
  774.     'Assert' => [],
  775.     'UnsignedChars' => 0,
  776.     'DoubleSize' => 8,
  777.     'EnumType' => 'Integer',
  778.     'PointerSize' => 4,
  779.     'EnumSize' => 4,
  780.     'DisabledKeywords' => [],
  781.     'FloatSize' => 4,
  782.     'LongLongSize' => 8,
  783.     'Alignment' => 1,
  784.     'LongDoubleSize' => 12,
  785.     'KeywordMap' => {},
  786.     'HasCPPComments' => 1,
  787.     'Include' => [
  788.       '/usr/include'
  789.     ],
  790.     'Warnings' => 0
  791.   };
  792.  
  793. Since you may not always want to write a L<C<configure>|/"configure"> call
  794. when you only want to change a single configuration item, you can
  795. use any configuration option name as a method name, like:
  796.  
  797.   $c->ByteOrder( 'LittleEndian' ) if $c->IntSize < 4;
  798.  
  799. (Yes, the example doesn't make very much sense... ;-)
  800.  
  801. However, you should keep in mind that configuration methods
  802. that can take lists (namely C<Include>, C<Define> and C<Assert>,
  803. but not C<DisabledKeywords>) may behave slightly different than
  804. their L<C<configure>|/"configure"> equivalent.
  805. If you pass these methods a single argument that is an array
  806. reference, the current list will be B<replaced> by the new one,
  807. which is just the behaviour of the
  808. corresponding L<C<configure>|/"configure"> call.
  809. So the following are equivalent:
  810.  
  811.   $c->configure( Define => ['foo', 'bar=123'] );
  812.   $c->Define( ['foo', 'bar=123'] );
  813.  
  814. But if you pass a list of strings instead of an array reference
  815. (which cannot be done when using L<C<configure>|/"configure">),
  816. the new list items are B<appended> to the current list, so
  817.  
  818.   $c = new Convert::Binary::C Include => ['/include'];
  819.   $c->Include( '/usr/include', '/usr/local/include' );
  820.   print Dumper( $c->Include );
  821.   
  822.   $c->Include( ['/usr/local/include'] );
  823.   print Dumper( $c->Include );
  824.  
  825. will first print all three include paths, but finally
  826. only C</usr/local/include> will be configured:
  827.  
  828.   $VAR1 = [
  829.     '/include',
  830.     '/usr/include',
  831.     '/usr/local/include'
  832.   ];
  833.   $VAR1 = [
  834.     '/usr/local/include'
  835.   ];
  836.  
  837. Furthermore, configuration methods can be chained together,
  838. as they return a reference to their object if called as a
  839. set method. So, if you like, you can configure your object
  840. like this:
  841.  
  842.   $c = Convert::Binary::C->new( IntSize => 4 )
  843.          ->Define( qw( __DEBUG__ DB_LEVEL=3 ) )
  844.          ->ByteOrder( 'BigEndian' );
  845.   
  846.   $c->configure( EnumType => 'Both', Alignment => 4 )
  847.     ->Include( '/usr/include', '/usr/local/include' );
  848.  
  849. In the example above, C<qw( ... )> is the word list quoting
  850. operator. It returns a list of all non-whitespace sequences,
  851. and is especially useful for configuring preprocessor defines
  852. or assertions. The following assignments are equivalent:
  853.  
  854.   @array = ('one', 'two', 'three');
  855.   @array = qw(one two three);
  856.  
  857. You can configure the following options. Unknown options, as well
  858. as invalid values for an option, will cause the object to throw
  859. exceptions.
  860.  
  861. =over 4
  862.  
  863. =item C<IntSize> =E<gt> 0 | 1 | 2 | 4 | 8
  864.  
  865. Set the number of bytes that are occupied by an integer. This is
  866. in most cases 2 or 4. If you set it to zero, the size of an
  867. integer on the host system will be used. This is also the
  868. default.
  869.  
  870. =item C<ShortSize> =E<gt> 0 | 1 | 2 | 4 | 8
  871.  
  872. Set the number of bytes that are occupied by a short integer.
  873. Although integers explicitly declared as C<short> should be
  874. always 16 bit, there are compilers that make a short
  875. 8 bit wide. If you set it to zero, the size of a short
  876. integer on the host system will be used. This is also the
  877. default.
  878.  
  879. =item C<LongSize> =E<gt> 0 | 1 | 2 | 4 | 8
  880.  
  881. Set the number of bytes that are occupied by a long integer.
  882. If set to zero, the size of a long integer on the host system
  883. will be used. This is also the default.
  884.  
  885. =item C<LongLongSize> =E<gt> 0 | 1 | 2 | 4 | 8
  886.  
  887. Set the number of bytes that are occupied by a long long
  888. integer. If set to zero, the size of a long long integer
  889. on the host system, or 8, will be used. This is also the
  890. default.
  891.  
  892. =item C<FloatSize> =E<gt> 0 | 1 | 2 | 4 | 8 | 12 | 16
  893.  
  894. Set the number of bytes that are occupied by a single
  895. precision floating point value.
  896. If you set it to zero, the size of a C<float> on the
  897. host system will be used. This is also the default.
  898. Values can only be packed and unpacked if the size
  899. matches the native size of a C<float>.
  900.  
  901. =item C<DoubleSize> =E<gt> 0 | 1 | 2 | 4 | 8 | 12 | 16
  902.  
  903. Set the number of bytes that are occupied by a double
  904. precision floating point value.
  905. If you set it to zero, the size of a C<double> on the
  906. host system will be used. This is also the default.
  907. Values can only be packed and unpacked if the size
  908. matches the native size of a C<double>.
  909.  
  910. =item C<LongDoubleSize> =E<gt> 0 | 1 | 2 | 4 | 8 | 12 | 16
  911.  
  912. Set the number of bytes that are occupied by a double
  913. precision floating point value.
  914. If you set it to zero, the size of a C<long double> on
  915. the host system, or 12 will be used. This is also the
  916. default. Values can only be packed and unpacked if the
  917. size matches the native size of a C<long double>.
  918.  
  919. =item C<PointerSize> =E<gt> 0 | 1 | 2 | 4 | 8
  920.  
  921. Set the number of bytes that are occupied by a pointer. This is
  922. in most cases 2 or 4. If you set it to zero, the size of a
  923. pointer on the host system will be used. This is also the
  924. default.
  925.  
  926. =item C<EnumSize> =E<gt> -1 | 0 | 1 | 2 | 4 | 8
  927.  
  928. Set the number of bytes that are occupied by an enumeration type.
  929. On most systems, this is equal to the size of an integer,
  930. which is also the default. However, for some compilers, the
  931. size of an enumeration type depends on the size occupied by the
  932. largest enumerator. So the size may vary between 1 and 8. If you
  933. have
  934.  
  935.   enum foo {
  936.     ONE = 100, TWO = 200
  937.   };
  938.  
  939. this will occupy one byte because the enum can be represented
  940. as an unsigned one-byte value. However,
  941.  
  942.   enum foo {
  943.     ONE = -100, TWO = 200
  944.   };
  945.  
  946. will occupy two bytes, because the -100 forces the type to
  947. be signed, and 200 doesn't fit into a signed one-byte value.
  948. Therefore, the type used is a signed two-byte value.
  949. If this is the behaviour you need, set the EnumSize to C<0>.
  950.  
  951. Some compilers try to follow this strategy, but don't care
  952. whether the enumeration has signed values or not. They always
  953. declare an enum as signed. On such a compiler, given
  954.  
  955.   enum one { ONE = -100, TWO = 100 };
  956.   enum two { ONE =  100, TWO = 200 };
  957.  
  958. enum C<one> will occupy only one byte, while enum C<two>
  959. will occupy two bytes, even though it could be represented
  960. by a unsigned one-byte value. If this is the behaviour of
  961. your compiler, set EnumSize to C<-1>.
  962.  
  963. =item C<Alignment> =E<gt> 1 | 2 | 4 | 8 | 16
  964.  
  965. Set the struct member alignment. This option controls where
  966. padding bytes are inserted between struct members. It globally
  967. sets the alignment for all structs/unions. However, this can
  968. be overridden from within the source code with the
  969. common C<pack> pragma as explained in L<"Supported pragma directives">.
  970. The default alignment is 1, which means no padding bytes are
  971. inserted.
  972.  
  973. The C<Alignment> option is similar to the C<-Zp[n]> option
  974. of the Intel compiler. It globally specifies the maximum
  975. boundary to which struct members are aligned. Consider the
  976. following structure and the sizes
  977. of C<char>, C<short>, C<long> and C<double> being 1, 2, 4
  978. and 8, respectively.
  979.  
  980.   struct align {
  981.     char   a;
  982.     short  b, c;
  983.     long   d;
  984.     double e;
  985.   };
  986.  
  987. With an alignment of 1 (the default), the struct members would
  988. be packed tightly:
  989.  
  990.   0   1   2   3   4   5   6   7   8   9  10  11  12
  991.   +---+---+---+---+---+---+---+---+---+---+---+---+
  992.   | a |   b   |   c   |       d       |             ...
  993.   +---+---+---+---+---+---+---+---+---+---+---+---+
  994.   
  995.      12  13  14  15  16  17
  996.       +---+---+---+---+---+
  997.   ...     e               |
  998.       +---+---+---+---+---+
  999.  
  1000. With an alignment of 2, the struct members larger than one byte
  1001. would be aligned to 2-byte boundaries, which results in a single
  1002. padding byte between C<a> and C<b>.
  1003.  
  1004.   0   1   2   3   4   5   6   7   8   9  10  11  12
  1005.   +---+---+---+---+---+---+---+---+---+---+---+---+
  1006.   | a | * |   b   |   c   |       d       |         ...
  1007.   +---+---+---+---+---+---+---+---+---+---+---+---+
  1008.   
  1009.      12  13  14  15  16  17  18
  1010.       +---+---+---+---+---+---+
  1011.   ...         e               |
  1012.       +---+---+---+---+---+---+
  1013.  
  1014. With an alignment of 4, the struct members of size 2 would be
  1015. aligned to 2-byte boundaries and larger struct members would
  1016. be aligned to 4-byte boundaries:
  1017.  
  1018.   0   1   2   3   4   5   6   7   8   9  10  11  12
  1019.   +---+---+---+---+---+---+---+---+---+---+---+---+
  1020.   | a | * |   b   |   c   | * | * |       d       | ...
  1021.   +---+---+---+---+---+---+---+---+---+---+---+---+
  1022.   
  1023.      12  13  14  15  16  17  18  19  20
  1024.       +---+---+---+---+---+---+---+---+
  1025.   ... |               e               |
  1026.       +---+---+---+---+---+---+---+---+
  1027.  
  1028. This layout of the struct members allows the compiler to generate
  1029. optimized code because aligned members can be accessed more easily
  1030. by the underlying architecture.
  1031.  
  1032. Finally, setting the alignment to 8 will align C<double>s to
  1033. 8-byte boundaries:
  1034.  
  1035.   0   1   2   3   4   5   6   7   8   9  10  11  12
  1036.   +---+---+---+---+---+---+---+---+---+---+---+---+
  1037.   | a | * |   b   |   c   | * | * |       d       | ...
  1038.   +---+---+---+---+---+---+---+---+---+---+---+---+
  1039.   
  1040.      12  13  14  15  16  17  18  19  20  21  22  23  24
  1041.       +---+---+---+---+---+---+---+---+---+---+---+---+
  1042.   ... | * | * | * | * |               e               |
  1043.       +---+---+---+---+---+---+---+---+---+---+---+---+
  1044.  
  1045. Further increasing the alignment does not alter the layout of
  1046. our structure, as only members larger that 8 bytes would be
  1047. affected.
  1048.  
  1049. The alignment of a structure depends on its largest member and
  1050. on the setting of the C<Alignment> option. With C<Alignment> set
  1051. to 2, a structure holding a C<long> would be aligned to a 2-byte
  1052. boundary, while a structure containing only C<char>s would have
  1053. no alignment restrictions.
  1054.  
  1055. Here's another example. Assuming 8-byte alignment, the following
  1056. two structs will both have a size of 16 bytes:
  1057.  
  1058.   struct one {
  1059.     char   c;
  1060.     double d;
  1061.   };
  1062.   
  1063.   struct two {
  1064.     double d;
  1065.     char   c;
  1066.   };
  1067.  
  1068. This is clear for C<struct one>, because the member C<d> has to
  1069. be aligned to an 8-byte boundary, and thus 7 padding bytes are
  1070. inserted after C<c>. But for C<struct two>, the padding bytes
  1071. are inserted I<at the end> of the structure, which doesn't make
  1072. much sense immediately. However, it makes perfect sense if you
  1073. think about an array of C<struct two>. Each C<double> has to be
  1074. aligned to an 8-byte boundary, an thus each array element would
  1075. have to occupy 16 bytes. With that in mind, it would be strange
  1076. if a C<struct two> variable would have a different size. And it
  1077. would make the widely used construct
  1078.  
  1079.   struct two array[] = { {1.0, 0}, {2.0, 1} };
  1080.   int elements = sizeof(array) / sizeof(struct two);
  1081.  
  1082. impossible.
  1083.  
  1084. The alignment behaviour described here seems to be common for all
  1085. compilers. However, not all compilers have an option to configure
  1086. their default alignment.
  1087.  
  1088. =item C<ByteOrder> =E<gt> 'BigEndian' | 'LittleEndian'
  1089.  
  1090. Set the byte order for integers larger than a single byte.
  1091. Little endian (Intel, least significant byte first) and
  1092. big endian (Motorola, most significant byte first) byte
  1093. order are supported. The default byte order is the same as
  1094. the byte order of the host system.
  1095.  
  1096. =item C<EnumType> =E<gt> 'Integer' | 'String' | 'Both'
  1097.  
  1098. This option controls the type that enumeration constants
  1099. will have in data structures returned by the L<C<unpack>|/"unpack"> method.
  1100. If you have the following definitions:
  1101.  
  1102.   typedef enum {
  1103.     SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
  1104.     THURSDAY, FRIDAY, SATURDAY
  1105.   } Weekday;
  1106.   
  1107.   typedef enum {
  1108.     JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY,
  1109.     AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
  1110.   } Month;
  1111.   
  1112.   typedef struct {
  1113.     int     year;
  1114.     Month   month;
  1115.     int     day;
  1116.     Weekday weekday;
  1117.   } Date;
  1118.  
  1119. and a byte string that holds a packed Date struct,
  1120. then you'll get the following results from a call
  1121. to the L<C<unpack>|/"unpack"> method.
  1122.  
  1123. =over 4
  1124.  
  1125. =item C<Integer>
  1126.  
  1127. Enumeration constants are returned as plain integers. This
  1128. is fast, but may be not very useful. It is also the default.
  1129.  
  1130.   $date = {
  1131.     'weekday' => 1,
  1132.     'month' => 0,
  1133.     'day' => 7,
  1134.     'year' => 2002
  1135.   };
  1136.  
  1137. =item C<String>
  1138.  
  1139. Enumeration constants are returned as strings. This will
  1140. create a string constant for every unpacked enumeration
  1141. constant and thus consumes more time and memory. However,
  1142. the result may be more useful.
  1143.  
  1144.   $date = {
  1145.     'weekday' => 'MONDAY',
  1146.     'month' => 'JANUARY',
  1147.     'day' => 7,
  1148.     'year' => 2002
  1149.   };
  1150.  
  1151. =item C<Both>
  1152.  
  1153. Enumeration constants are returned as double typed scalars.
  1154. If evaluated in string context, the enumeration constant
  1155. will be a string, if evaluated in numeric context, the
  1156. enumeration constant will be an integer.
  1157.  
  1158.   $date = $c->EnumType('Both')->unpack('Date', $binary);
  1159.   
  1160.   printf "Weekday = %s (%d)\n\n", $date->{weekday},
  1161.                                   $date->{weekday};
  1162.   
  1163.   if( $date->{month} == 0 ) {
  1164.     print "It's $date->{month}, happy new year!\n\n";
  1165.   }
  1166.   
  1167.   print Dumper( $date );
  1168.  
  1169. This will print:
  1170.  
  1171.   Weekday = MONDAY (1)
  1172.   
  1173.   It's JANUARY, happy new year!
  1174.   
  1175.   $VAR1 = {
  1176.     'weekday' => 'MONDAY',
  1177.     'month' => 'JANUARY',
  1178.     'day' => 7,
  1179.     'year' => 2002
  1180.   };
  1181.  
  1182. =back
  1183.  
  1184. =item C<DisabledKeywords> =E<gt> [ KEYWORDS ]
  1185.  
  1186. This option allows you to selectively deactivate certain
  1187. keywords in the C parser. Some C compilers don't have
  1188. the complete ANSI keyword set, i.e. they don't recognize
  1189. the keywords C<const> or C<void>, for example. If you do
  1190.  
  1191.   typedef int void;
  1192.  
  1193. on such a compiler, this will usually be ok. But if you
  1194. parse this with an ANSI compiler, it will be a syntax
  1195. error. To parse the above code correctly, you have to
  1196. disable the C<void> keyword in the Convert::Binary::C
  1197. parser:
  1198.  
  1199.   $c->DisabledKeywords( [qw( void )] );
  1200.  
  1201. By default, the Convert::Binary::C parser will recognize
  1202. the keywords C<inline> and C<restrict>. If your compiler
  1203. doesn't have these new keywords, it usually doesn't matter.
  1204. Only if you're using the keywords as identifiers, like in
  1205.  
  1206.   typedef struct inline {
  1207.     int a, b;
  1208.   } restrict;
  1209.  
  1210. you'll have to disable these ISO-C99 keywords:
  1211.  
  1212.   $c->DisabledKeywords( [qw( inline restrict )] );
  1213.  
  1214. The parser allows you to disable the following keywords:
  1215.  
  1216.   auto
  1217.   const
  1218.   double
  1219.   enum
  1220.   extern
  1221.   float
  1222.   inline
  1223.   long
  1224.   register
  1225.   restrict
  1226.   short
  1227.   signed
  1228.   static
  1229.   unsigned
  1230.   void
  1231.   volatile
  1232.  
  1233. =item C<KeywordMap> =E<gt> { KEYWORD =E<gt> TOKEN, ... }
  1234.  
  1235. This option allows you to add new keywords to the parser.
  1236. These new keywords can either be mapped to existing tokens
  1237. or simply ignored. For example, recent versions of the GNU
  1238. compiler recognize the keywords C<__signed__> and C<__extension__>.
  1239. The first one obviously is a synonym for C<signed>, while
  1240. the second one is only a marker for a language extension.
  1241.  
  1242. Using the preprocessor, you could of course do the following:
  1243.  
  1244.   $c->Define( qw( __signed__=signed __extension__= ) );
  1245.  
  1246. However, the preprocessor symbols could be undefined or
  1247. redefined in the code, and
  1248.  
  1249.   #ifdef __signed__
  1250.   # undef __signed__
  1251.   #endif
  1252.   
  1253.   typedef __extension__ __signed__ long long s_quad;
  1254.  
  1255. would generate a parse error, because C<__signed__> is an
  1256. unexpected identifier.
  1257.  
  1258. Instead of utilizing the preprocessor, you'll have to create
  1259. mappings for the new keywords directly in the parser
  1260. using C<KeywordMap>. In the above example, you want to
  1261. map C<__signed__> to the builtin C keyword C<signed> and
  1262. ignore C<__extension__>. This could be done with the following
  1263. code:
  1264.  
  1265.   $c->KeywordMap( {
  1266.                     __signed__    => 'signed',
  1267.                     __extension__ => undef,
  1268.                   } );
  1269.  
  1270. You can specify any valid identifier as hash key, and either
  1271. a valid C keyword or C<undef> as hash value.
  1272. Having configured the object that way, you could parse even
  1273.  
  1274.   #ifdef __signed__
  1275.   # undef __signed__
  1276.   #endif
  1277.   
  1278.   typedef __extension__ __signed__ long long s_quad;
  1279.  
  1280. without problems.
  1281.  
  1282. Note that C<KeywordMap> and C<DisabledKeywords> perfectly work
  1283. together. You could, for example, disable the C<signed> keyword,
  1284. but still have C<__signed__> mapped to the original C<signed> token:
  1285.  
  1286.   $c->configure( DisabledKeywords => [ 'signed' ],
  1287.                  KeywordMap       => { __signed__  => 'signed' } );
  1288.  
  1289. This would allow you to define
  1290.  
  1291.   typedef __signed__ long signed;
  1292.  
  1293. which would normally be a syntax error because C<signed> cannot
  1294. be used as an identifier.
  1295.  
  1296. =item C<UnsignedChars> =E<gt> 0 | 1
  1297.  
  1298. Use this boolean option if you want characters
  1299. to be unsigned if specified without an
  1300. explicit C<signed> or C<unsigned> type specifier.
  1301. By default, characters are signed.
  1302.  
  1303. =item C<Warnings> =E<gt> 0 | 1
  1304.  
  1305. Use this boolean option if you want warnings to be issued
  1306. during the parsing of source code. Currently, warnings
  1307. are only reported by the preprocessor, so don't expect
  1308. the output to cover everything.
  1309.  
  1310. By default, warnings are turned off and only errors will be
  1311. reported. However, even these errors are turned off if
  1312. you run without the C<-w> flag.
  1313.  
  1314. =item C<HasCPPComments> =E<gt> 0 | 1
  1315.  
  1316. Use this option to turn C++ comments on or off. By default,
  1317. C++ comments are enabled. Disabling C++ comments may be
  1318. necessary if your code includes strange things like:
  1319.  
  1320.   one = 4 //* <- divide */ 4;
  1321.   two = 2;
  1322.  
  1323. With C++ comments, the above will be interpreted as
  1324.  
  1325.   one = 4
  1326.   two = 2;
  1327.  
  1328. which will obviously be a syntax error, but without
  1329. C++ comments, it will be interpreted as
  1330.  
  1331.   one = 4 / 4;
  1332.   two = 2;
  1333.  
  1334. which is correct.
  1335.  
  1336. =item C<HasMacroVAARGS> =E<gt> 0 | 1
  1337.  
  1338. Use this option to turn the C<__VA_ARGS__> macro expansion
  1339. on or off. If this is enabled (which is the default), you can use
  1340. variable length argument lists in your preprocessor macros.
  1341.  
  1342.   #define DEBUG( ... )  fprintf( stderr, __VA_ARGS__ )
  1343.  
  1344. There's normally no reason to turn that feature off.
  1345.  
  1346. =item C<Include> =E<gt> [ INCLUDES ]
  1347.  
  1348. Use this option to set the include path for the internal
  1349. preprocessor. The option value is a reference to an array
  1350. of strings, each string holding a directory that should
  1351. be searched for includes.
  1352.  
  1353. =item C<Define> =E<gt> [ DEFINES ]
  1354.  
  1355. Use this option to define symbols in the preprocessor.
  1356. The option value is, again, a reference to an array of
  1357. strings. Each string can be either just a symbol or an
  1358. assignment to a symbol. This is completely equivalent
  1359. to what the C<-D> option does for most preprocessors.
  1360.  
  1361. The following will define the symbol C<FOO> and
  1362. define C<BAR> to be C<12345>:
  1363.  
  1364.   $c->configure( Define => [qw(FOO BAR=12345)] );
  1365.  
  1366. =item C<Assert> =E<gt> [ ASSERTIONS ]
  1367.  
  1368. Use this option to make assertions in the preprocessor.
  1369. If you don't know what assertions are, don't be
  1370. concerned, since they're deprecated anyway. They
  1371. are, however, used in some system's include files.
  1372. The value is an array reference, just like for the
  1373. macro definitions. Only the way the assertions are
  1374. defined is a bit different and mimics the way they
  1375. are defined with the C<#assert> directive:
  1376.  
  1377.   $c->configure( Assert => ['foo(bar)'] );
  1378.  
  1379. =back
  1380.  
  1381. You can reconfigure all options even after you have
  1382. parsed some code. The changes will be applied to the
  1383. already parsed definitions. This works as long as array
  1384. lengths are not affected by the changes. If you have
  1385. Alignment and IntSize set to 4 and parse code like
  1386. this
  1387.  
  1388.   typedef struct {
  1389.     char abc;
  1390.     int  day;
  1391.   } foo;
  1392.   
  1393.   struct bar {
  1394.     foo  zap[2*sizeof(foo)];
  1395.   };
  1396.  
  1397. the array C<zap> in C<struct bar> will obviously have
  1398. 16 elements. If you reconfigure the alignment to 1 now,
  1399. the size of C<foo> is now 5 instead of 8. While the
  1400. alignment is adjusted correctly, the number of elements
  1401. in array C<zap> will still be 16 and will not be changed
  1402. to 10.
  1403.  
  1404. =back
  1405.  
  1406. =head2 parse
  1407.  
  1408. =over 8
  1409.  
  1410. =item C<parse> CODE
  1411.  
  1412. Parses a string of valid C code. All enumeration, compound
  1413. and type definitions are extracted. You can call
  1414. the L<C<parse>|/"parse"> and L<C<parse_file>|/"parse_file"> methods
  1415. as often as you like to add further definitions to the
  1416. Convert::Binary::C object.
  1417.  
  1418. L<C<parse>|/"parse"> will throw an exception if an error occurs.
  1419. On success, the method returns a reference to its object.
  1420.  
  1421. See L<"Parsing C code"> for an example.
  1422.  
  1423. =back
  1424.  
  1425. =head2 parse_file
  1426.  
  1427. =over 8
  1428.  
  1429. =item C<parse_file> FILE
  1430.  
  1431. Parses a C source file. All enumeration, compound and type
  1432. definitions are extracted. You can call
  1433. the L<C<parse>|/"parse"> and L<C<parse_file>|/"parse_file"> methods
  1434. as often as you like to add further definitions to the
  1435. Convert::Binary::C object.
  1436.  
  1437. L<C<parse_file>|/"parse_file"> will throw an exception if an error
  1438. occurs. On success, the method returns a reference to its object.
  1439.  
  1440. See L<"Parsing C code"> for an example.
  1441.  
  1442. You must be aware that the preprocessor is reset with every call
  1443. to L<C<parse>|/"parse"> or L<C<parse_file>|/"parse_file">.
  1444. Also, you may use types previously defined, but you are not allowed
  1445. to redefine types.
  1446.  
  1447. When you're parsing C source files instead of C header
  1448. files, note that local definitions are ignored. This means
  1449. that type definitions hidden within functions will not be
  1450. recognized by Convert::Binary::C. This is necessary
  1451. because different functions (even different blocks within
  1452. the same function) can define types with the same name:
  1453.  
  1454.   void my_func( int i )
  1455.   {
  1456.     if( i < 10 ) {
  1457.       enum digit { ONE, TWO, THREE } x = ONE;
  1458.       printf("%d, %d\n", i, x);
  1459.     }
  1460.     else {
  1461.       enum digit { THREE, TWO, ONE } x = ONE;
  1462.       printf("%d, %d\n", i, x);
  1463.     }
  1464.   }
  1465.  
  1466. The above is a valid piece of C code, but it's not possible
  1467. for Convert::Binary::C to distinguish between the different
  1468. definitions of C<enum digit>, as they're only defined
  1469. locally within the corresponding block.
  1470.  
  1471. =back
  1472.  
  1473. =head2 clean
  1474.  
  1475. =over 8
  1476.  
  1477. =item C<clean>
  1478.  
  1479. Clears all information that has been collected during previous
  1480. calls to L<C<parse>|/"parse"> or L<C<parse_file>|/"parse_file">.
  1481. You can use this method if you want to parse some entirely
  1482. different code, but with the same configuration.
  1483.  
  1484. The L<C<clean>|/"clean"> method returns a reference to its object.
  1485.  
  1486. =back
  1487.  
  1488. =head2 clone
  1489.  
  1490. =over 8
  1491.  
  1492. =item C<clone>
  1493.  
  1494. Makes the object return an exact independent copy of itself.
  1495.  
  1496.   $c = new Convert::Binary::C Include => ['/usr/include'];
  1497.   $c->parse_file( 'definitions.c' );
  1498.   $clone = $c->clone;
  1499.  
  1500. The above code is technically equivalent (Mostly. Actually,
  1501. using L<C<sourcify>|/"sourcify"> and L<C<parse>|/"parse"> might alter
  1502. the order of the parsed data, which would make methods such
  1503. as L<C<compound>|/"compound"> return the definitions in a different
  1504. order.) to:
  1505.  
  1506.   $c = new Convert::Binary::C Include => ['/usr/include'];
  1507.   $c->parse_file( 'definitions.c' );
  1508.   $clone = new Convert::Binary::C %{$c->configure};
  1509.   $clone->parse( $c->sourcify );
  1510.  
  1511. Using L<C<clone>|/"clone"> is just a lot faster.
  1512.  
  1513. =back
  1514.  
  1515. =head2 def
  1516.  
  1517. =over 8
  1518.  
  1519. =item C<def> NAME
  1520.  
  1521. If you need to know if a definition for a certain type name
  1522. exists, use this method. You pass it the name of an enum,
  1523. struct, union or typedef, and it will return a non-empty
  1524. string being either C<"enum">, C<"struct">, C<"union">,
  1525. or C<"typedef"> if there's a definition for the type in
  1526. question, an empty string if there's no such definition,
  1527. or C<undef> if the name is completely unknown. If the
  1528. type can be interpreted as a basic type, C<"basic"> will
  1529. be returned.
  1530.  
  1531.   use Convert::Binary::C;
  1532.   
  1533.   my $c = Convert::Binary::C->new->parse( <<'ENDC' );
  1534.   
  1535.   typedef struct __not  not;
  1536.   typedef struct __not *ptr;
  1537.   
  1538.   struct foo {
  1539.     enum bar *xxx;
  1540.   };
  1541.   
  1542.   ENDC
  1543.   
  1544.   for my $type ( qw( not ptr foo bar xxx ),
  1545.                  'unsigned long' )
  1546.   {
  1547.     my $def = $c->def( $type );
  1548.     printf "\$c->def( '$type' )  =>  %s\n",
  1549.            defined $def ? "'$def'" : 'undef';
  1550.   }
  1551.  
  1552. The following would be returned by the L<C<def>|/"def"> method:
  1553.  
  1554.   $c->def( 'not' )  =>  ''
  1555.   $c->def( 'ptr' )  =>  'typedef'
  1556.   $c->def( 'foo' )  =>  'struct'
  1557.   $c->def( 'bar' )  =>  ''
  1558.   $c->def( 'xxx' )  =>  undef
  1559.   $c->def( 'unsigned long' )  =>  'basic'
  1560.  
  1561. So, if L<C<def>|/"def"> returns a non-empty string, you can safely use
  1562. any other method with that type's name.
  1563.  
  1564. In cases where the typedef namespace overlaps with the
  1565. namespace of enums/structs/unions, the L<C<def>|/"def"> method
  1566. will give preference to the typedef and will thus return
  1567. the string C<"typedef">. You could however force interpretation
  1568. as an enum, struct or union by putting C<"enum">, C<"struct">
  1569. or C<"union"> in front of the type's name.
  1570.  
  1571. =back
  1572.  
  1573. =head2 pack
  1574.  
  1575. =over 8
  1576.  
  1577. =item C<pack> TYPE, DATA
  1578.  
  1579. =item C<pack> TYPE, DATA, STRING
  1580.  
  1581. Use this method to pack a complex data structure into a
  1582. binary string according to a type definition that has been
  1583. previously parsed. DATA must be a scalar matching the
  1584. type definition. C structures and unions are represented
  1585. by references to Perl hashes, C arrays by references to
  1586. Perl arrays.
  1587.  
  1588.   use Convert::Binary::C;
  1589.   use Data::Dumper;
  1590.   use Data::Hexdumper;
  1591.   
  1592.   $c = Convert::Binary::C->new( ByteOrder => 'BigEndian',
  1593.                                 LongSize  => 4,
  1594.                                 ShortSize => 2 )
  1595.                          ->parse( <<'ENDC' );
  1596.   struct test {
  1597.     char    ary[3];
  1598.     union {
  1599.       short word[2];
  1600.       long  quad;
  1601.     }       uni;
  1602.   };
  1603.   ENDC
  1604.  
  1605. Hashes don't have to contain a key for each compound member
  1606. and arrays may be truncated:
  1607.  
  1608.   $binary = $c->pack( 'test', { ary => [1, 2], uni => { quad => 42 } } );
  1609.  
  1610. Elements not defined in the Perl data structure will be
  1611. set to zero in the packed byte string. On success, the
  1612. packed byte string is returned.
  1613.  
  1614.   print hexdump( data => $binary );
  1615.  
  1616. The above code would print:
  1617.  
  1618.     0x0000 : 01 02 00 00 00 00 2A                            : ......*
  1619.  
  1620. You could also use L<C<unpack>|/"unpack"> and dump the data structure.
  1621.  
  1622.   $unpacked = $c->unpack( 'test', $binary );
  1623.   print Data::Dumper->Dump( [$unpacked], ['unpacked'] );
  1624.  
  1625. This would print:
  1626.  
  1627.   $unpacked = {
  1628.     'uni' => {
  1629.       'word' => [
  1630.         0,
  1631.         42
  1632.       ],
  1633.       'quad' => 42
  1634.     },
  1635.     'ary' => [
  1636.       1,
  1637.       2,
  1638.       0
  1639.     ]
  1640.   };
  1641.  
  1642. If L<TYPE|/"UNDERSTANDING TYPES"> refers to a compound object, you may pack any
  1643. member of that compound object. Simply add a member string
  1644. to the type name, just as you would access the member in
  1645. C:
  1646.  
  1647.   $array = $c->pack( 'test.ary', [1, 2, 3] );
  1648.   print hexdump( data => $array );
  1649.   
  1650.   $value = $c->pack( 'test.uni.word[1]', 2 );
  1651.   print hexdump( data => $value );
  1652.  
  1653. This would give you:
  1654.  
  1655.     0x0000 : 01 02 03                                        : ...
  1656.     0x0000 : 00 02                                           : ..
  1657.  
  1658. Call L<C<pack>|/"pack"> with the optional STRING argument if you want
  1659. to use an existing binary string to insert the data.
  1660. If called in a void context, L<C<pack>|/"pack"> will directly
  1661. modify the string you passed as the third argument.
  1662. Otherwise, a copy of the string is created, and L<C<pack>|/"pack"> will
  1663. modify and return the copy, so the original string
  1664. will remain unchanged.
  1665.  
  1666. The 3-argument version may be useful if you want to change
  1667. only a few members of a complex data structure without
  1668. having to L<C<unpack>|/"unpack"> everything, change the members, and
  1669. then L<C<pack>|/"pack"> again (which could waste lots of memory
  1670. and CPU cycles). So, instead of doing something like
  1671.  
  1672.   $test = $c->unpack( 'test', $binary );
  1673.   $test->{uni}{quad} = 4711;
  1674.   $new = $c->pack( 'test', $test );
  1675.  
  1676. to change the C<uni.quad> member of C<$packed>, you
  1677. could simply do either
  1678.  
  1679.   $new = $c->pack( 'test', { uni => { quad => 4711 } }, $binary );
  1680.  
  1681. or
  1682.  
  1683.   $c->pack( 'test', { uni => { quad => 4711 } }, $binary );
  1684.  
  1685. while the latter would directly modify C<$packed>.
  1686. Besides this code being a lot shorter (and perhaps even
  1687. more readable), it can be significantly faster if you're
  1688. dealing with really big data blocks.
  1689.  
  1690. If the length of the input string is less than the size
  1691. required by the type, the string (or its copy) is
  1692. extended and the extended part is initialized to zero.
  1693. If the length is more than the size required by the type,
  1694. the string is kept at that length, and also a copy would
  1695. be an exact copy of that string.
  1696.  
  1697.   $too_short = pack "C*", (1 .. 4);
  1698.   $too_long  = pack "C*", (1 .. 20);
  1699.   
  1700.   $c->pack( 'test', { uni => { quad => 0x4711 } }, $too_short );
  1701.   print "too_short:\n", hexdump( data => $too_short );
  1702.   
  1703.   $copy = $c->pack( 'test', { uni => { quad => 0x4711 } }, $too_long );
  1704.   print "\ncopy:\n", hexdump( data => $copy );
  1705.  
  1706. This would print:
  1707.  
  1708.   too_short:
  1709.     0x0000 : 01 02 03 00 00 47 11                            : .....G.
  1710.   
  1711.   copy:
  1712.     0x0000 : 01 02 03 00 00 47 11 08 09 0A 0B 0C 0D 0E 0F 10 : .....G..........
  1713.     0x0010 : 11 12 13 14                                     : ....
  1714.  
  1715. =back
  1716.  
  1717. =head2 unpack
  1718.  
  1719. =over 8
  1720.  
  1721. =item C<unpack> TYPE, STRING
  1722.  
  1723. Use this method to unpack a binary string and create an
  1724. arbitrarily complex Perl data structure based on a
  1725. previously parsed type definition.
  1726.  
  1727.   use Convert::Binary::C;
  1728.   use Data::Dumper;
  1729.   
  1730.   $c = Convert::Binary::C->new( ByteOrder => 'BigEndian',
  1731.                                 LongSize  => 4,
  1732.                                 ShortSize => 2 )
  1733.                          ->parse( <<'ENDC' );
  1734.   struct test {
  1735.     char    ary[3];
  1736.     union {
  1737.       short word[2];
  1738.       long *quad;
  1739.     }       uni;
  1740.   };
  1741.   ENDC
  1742.   
  1743.   # Generate some binary dummy data
  1744.   $binary = pack "C*", (1 .. $c->sizeof('test'));
  1745.  
  1746. On failure, e.g. if the specified type cannot be found, the
  1747. method will throw an exception. On success, a reference to
  1748. a complex Perl data structure is returned, which can directly
  1749. be dumped using the L<Data::Dumper|Data::Dumper> module:
  1750.  
  1751.   $unpacked = $c->unpack( 'test', $binary );
  1752.   print Dumper( $unpacked );
  1753.  
  1754. This would print:
  1755.  
  1756.   $VAR1 = {
  1757.     'uni' => {
  1758.       'word' => [
  1759.         1029,
  1760.         1543
  1761.       ],
  1762.       'quad' => 67438087
  1763.     },
  1764.     'ary' => [
  1765.       1,
  1766.       2,
  1767.       3
  1768.     ]
  1769.   };
  1770.  
  1771. If L<TYPE|/"UNDERSTANDING TYPES"> refers to a compound object, you may unpack any
  1772. member of that compound object. Simply add a member string
  1773. to the type name, just as you would access the member in
  1774. C:
  1775.  
  1776.   $binary2 = substr $binary, $c->offsetof('test', 'uni.word');
  1777.   
  1778.   $unpack1 = $unpacked->{uni}{word};
  1779.   $unpack2 = $c->unpack( 'test.uni.word', $binary2 );
  1780.   
  1781.   print Data::Dumper->Dump( [$unpack1, $unpack2], [qw(unpack1 unpack2)] );
  1782.  
  1783. You will find that the output is exactly the same for
  1784. both C<$unpack1> and C<$unpack2>:
  1785.  
  1786.   $unpack1 = [
  1787.     1029,
  1788.     1543
  1789.   ];
  1790.   $unpack2 = [
  1791.     1029,
  1792.     1543
  1793.   ];
  1794.  
  1795. =back
  1796.  
  1797. =head2 sizeof
  1798.  
  1799. =over 8
  1800.  
  1801. =item C<sizeof> TYPE
  1802.  
  1803. This method will return the size of a C type in bytes.
  1804. If it cannot find the type, it will throw an exception.
  1805.  
  1806. If the type defines some kind of compound object, you
  1807. may ask for the size of a member of that compound object:
  1808.  
  1809.   $size = $c->sizeof( 'test.uni.word[1]' );
  1810.  
  1811. This would set C<$size> to C<2>.
  1812.  
  1813. =back
  1814.  
  1815. =head2 typeof
  1816.  
  1817. =over 8
  1818.  
  1819. =item C<typeof> TYPE
  1820.  
  1821. This method will return the type of a C member.
  1822. While this only makes sense for compound types, it's legal
  1823. to also use it for non-compound types.
  1824. If it cannot find the type, it will throw an exception.
  1825.  
  1826. The L<C<typeof>|/"typeof"> method can be used on any valid
  1827. member, even on arrays or unnamed types. It will always
  1828. return a string that holds the name (or in case of unnamed
  1829. types only the class) of the type, optionally followed by
  1830. a C<'*'> character to indicate it's a pointer type, and
  1831. optionally followed by one or more array dimensions if
  1832. it's an array type.
  1833.  
  1834.   for my $member ( qw( test test.uni test.uni.quad
  1835.                        test.uni.word test.uni.word[1] ) ) {
  1836.     printf "%-16s => '%s'\n", $member, $c->typeof( $member );
  1837.   }
  1838.  
  1839. This would print:
  1840.  
  1841.   test             => 'struct test'
  1842.   test.uni         => 'union'
  1843.   test.uni.quad    => 'long *'
  1844.   test.uni.word    => 'short [2]'
  1845.   test.uni.word[1] => 'short'
  1846.  
  1847. =back
  1848.  
  1849. =head2 offsetof
  1850.  
  1851. =over 8
  1852.  
  1853. =item C<offsetof> TYPE, MEMBER
  1854.  
  1855. You can use L<C<offsetof>|/"offsetof"> just like the C macro
  1856. of same denominator. It will simply return the offset (in bytes)
  1857. of L<MEMBER|/"Member Expressions"> relative to L<TYPE|/"UNDERSTANDING TYPES">.
  1858.  
  1859.   use Convert::Binary::C;
  1860.   
  1861.   $c = Convert::Binary::C->new( Alignment   => 4
  1862.                               , LongSize    => 4
  1863.                               , PointerSize => 4
  1864.                               )
  1865.                          ->parse( <<'ENDC' );
  1866.   typedef struct {
  1867.     char abc;
  1868.     long day;
  1869.     int *ptr;
  1870.   } week;
  1871.   
  1872.   struct test {
  1873.     week zap[8];
  1874.   };
  1875.   ENDC
  1876.   
  1877.   @args = (
  1878.     ['test',        'zap[5].day'  ],
  1879.     ['test.zap[2]', 'day'         ],
  1880.     ['test',        'zap[5].day+1'],
  1881.   );
  1882.   
  1883.   for( @args ) {
  1884.     my $offset = eval { $c->offsetof( @$_ ) };
  1885.     printf "\$c->offsetof( '%s', '%s' ) => $offset\n", @$_;
  1886.   }
  1887.  
  1888. The final loop will print:
  1889.  
  1890.   $c->offsetof( 'test', 'zap[5].day' ) => 64
  1891.   $c->offsetof( 'test.zap[2]', 'day' ) => 4
  1892.   $c->offsetof( 'test', 'zap[5].day+1' ) => 65
  1893.  
  1894. =over 2
  1895.  
  1896. =item *
  1897.  
  1898. The first iteration simply shows that the offset
  1899. of C<zap[5].day> is 64 relative to the beginning
  1900. of C<struct test>.
  1901.  
  1902. =item *
  1903.  
  1904. You may additionally specify a member for the type
  1905. passed as the first argument, as shown in the second
  1906. iteration.
  1907.  
  1908. =item *
  1909.  
  1910. Even the L<offset suffix|/"Offsets"> is supported
  1911. by L<C<offsetof>|/"offsetof">, so the third iteration
  1912. will correctly print 65.
  1913.  
  1914. =back
  1915.  
  1916. Unlike the C macro, L<C<offsetof>|/"offsetof"> also works
  1917. on array types.
  1918.  
  1919.   $offset = $c->offsetof( 'test.zap', '[3].ptr+2' );
  1920.   print "offset = $offset";
  1921.  
  1922. This will print:
  1923.  
  1924.   offset = 46
  1925.  
  1926. If L<TYPE|/"UNDERSTANDING TYPES"> is a
  1927. compound, L<MEMBER|/"Member Expressions"> may
  1928. optionally be prefixed with a dot, so
  1929.  
  1930.   printf "offset = %d\n", $c->offsetof( 'week', 'day' );
  1931.   printf "offset = %d\n", $c->offsetof( 'week', '.day' );
  1932.  
  1933. are both equivalent and will print
  1934.  
  1935.   offset = 4
  1936.   offset = 4
  1937.  
  1938. This allows to
  1939.  
  1940. =over 2
  1941.  
  1942. =item *
  1943.  
  1944. use the C macro style, without a leading dot, and
  1945.  
  1946. =item *
  1947.  
  1948. directly use the output of the L<C<member>|/"member"> method,
  1949. which includes a leading dot for compound types, as input for
  1950. the L<MEMBER|/"Member Expressions"> argument.
  1951.  
  1952. =back
  1953.  
  1954. =back
  1955.  
  1956. =head2 member
  1957.  
  1958. =over 8
  1959.  
  1960. =item C<member> TYPE, OFFSET
  1961.  
  1962. You can think of L<C<member>|/"member"> as being the reverse
  1963. of the L<C<offsetof>|/"offsetof"> method. However, as this is
  1964. more complex, there's no equivalent to L<C<member>|/"member"> in
  1965. the C language.
  1966.  
  1967. Use this method if you want to retrieve the name of the member
  1968. that is located at a specific offset of a previously parsed type.
  1969.  
  1970.   use Convert::Binary::C;
  1971.   
  1972.   $c = Convert::Binary::C->new( Alignment   => 4
  1973.                               , LongSize    => 4
  1974.                               , PointerSize => 4
  1975.                               )
  1976.                          ->parse( <<'ENDC' );
  1977.   typedef struct {
  1978.     char abc;
  1979.     long day;
  1980.     int *ptr;
  1981.   } week;
  1982.   
  1983.   struct test {
  1984.     week zap[8];
  1985.   };
  1986.   ENDC
  1987.   
  1988.   for my $offset ( 24, 39, 69, 99 ) {
  1989.     print "\$c->member( 'test', $offset )";
  1990.     my $member = eval { $c->member( 'test', $offset ) };
  1991.     print $@ ? "\n  exception: $@" : " => '$member'\n";
  1992.   }
  1993.  
  1994. This will print:
  1995.  
  1996.   $c->member( 'test', 24 ) => '.zap[2].abc'
  1997.   $c->member( 'test', 39 ) => '.zap[3]+3'
  1998.   $c->member( 'test', 69 ) => '.zap[5].ptr+1'
  1999.   $c->member( 'test', 99 )
  2000.     exception: Offset 99 out of range (0 <= offset < 96) 
  2001.  
  2002. =over 2
  2003.  
  2004. =item *
  2005.  
  2006. The output of the first iteration is obvious. The
  2007. member C<zap[2].abc> is located at offset 24 of C<struct test>.
  2008.  
  2009. =item *
  2010.  
  2011. In the second iteration, the offset points into a region
  2012. of padding bytes and thus no member of C<week> can be
  2013. named. Instead of a member name the offset relative
  2014. to C<zap[3]> is appended.
  2015.  
  2016. =item *
  2017.  
  2018. In the third iteration, the offset points to C<zap[5].ptr>.
  2019. However, C<zap[5].ptr> is located at 68, not at 69,
  2020. and thus the remaining offset of 1 is also appended.
  2021.  
  2022. =item *
  2023.  
  2024. The last iteration causes an exception because the offset
  2025. of 99 is not valid for C<struct test> since the size
  2026. of C<struct test> is only 96.
  2027.  
  2028. =back
  2029.  
  2030. You can additionally specify a member for the type passed
  2031. as the first argument:
  2032.  
  2033.   $member = $c->member('test.zap[2]', 6);
  2034.   print $member;
  2035.  
  2036. This will print:
  2037.  
  2038.   .day+2
  2039.  
  2040. Like L<C<offsetof>|/"offsetof">, L<C<member>|/"member"> also
  2041. works on array types:
  2042.  
  2043.   $member = $c->member('test.zap', 42);
  2044.   print $member;
  2045.  
  2046. This will print:
  2047.  
  2048.   [3].day+2
  2049.  
  2050. While the behaviour for C<struct>s is quite obvious, the behaviour
  2051. for C<union>s is rather tricky. As a single offset usually references
  2052. more than one member of a union, there are certain rules that the
  2053. algorithm uses for determining the I<best> member.
  2054.  
  2055. =over 2
  2056.  
  2057. =item *
  2058.  
  2059. The first non-compound member that is referenced without an offset
  2060. has the highest priority.
  2061.  
  2062. =item *
  2063.  
  2064. If no member is referenced without an offset, the first non-compound
  2065. member that is referenced with an offset will be returned.
  2066.  
  2067. =item *
  2068.  
  2069. Otherwise the first padding region that is encountered will be taken.
  2070.  
  2071. =back
  2072.  
  2073. As an example, given 4-byte-alignment and the union
  2074.  
  2075.   union choice {
  2076.     struct {
  2077.       char  color[2];
  2078.       long  size;
  2079.       char  taste;
  2080.     }       apple;
  2081.     char    grape[3];
  2082.     struct {
  2083.       long  weight;
  2084.       short price[3];
  2085.     }       melon;
  2086.   };
  2087.  
  2088. the L<C<member>|/"member"> method would return what is shown in
  2089. the I<Member> column of the following table. The I<Type> column
  2090. shows the result of the L<C<typeof>|/"typeof"> method when passing
  2091. the corresponding member.
  2092.  
  2093.   Offset   Member               Type
  2094.   --------------------------------------
  2095.      0     .apple.color[0]      'char'
  2096.      1     .apple.color[1]      'char'
  2097.      2     .grape[2]            'char'
  2098.      3     .melon.weight+3      'long'
  2099.      4     .apple.size          'long'
  2100.      5     .apple.size+1        'long'
  2101.      6     .melon.price[1]      'short'
  2102.      7     .apple.size+3        'long'
  2103.      8     .apple.taste         'char'
  2104.      9     .melon.price[2]+1    'short'
  2105.     10     .apple+10            'struct'
  2106.     11     .apple+11            'struct'
  2107.  
  2108. It's like having a stack of all the union members and looking through
  2109. the stack for the shiniest piece you can see. The beginning of a member
  2110. (denoted by uppercase letters) is always shinier than the rest of a
  2111. member, while padding regions (denoted by dashes) aren't shiny at all.
  2112.  
  2113.   Offset   0   1   2   3   4   5   6   7   8   9  10  11
  2114.   -------------------------------------------------------
  2115.   apple   (C) (C)  -   -  (S) (s)  s  (s) (T)  -  (-) (-)
  2116.   grape    G   G  (G)
  2117.   melon    W   w   w  (w)  P   p  (P)  p   P  (p)  -   -
  2118.  
  2119. If you look through that stack from top to bottom, you'll end up at
  2120. the parenthesized members.
  2121.  
  2122. Alternatively, if you're not only interested in the I<best> member,
  2123. you can call L<C<member>|/"member"> in list context, which makes it
  2124. return I<all> members referenced by the given offset.
  2125.  
  2126.   Offset   Member               Type
  2127.   --------------------------------------
  2128.      0     .apple.color[0]      'char'
  2129.            .grape[0]            'char'
  2130.            .melon.weight        'long'
  2131.      1     .apple.color[1]      'char'
  2132.            .grape[1]            'char'
  2133.            .melon.weight+1      'long'
  2134.      2     .grape[2]            'char'
  2135.            .melon.weight+2      'long'
  2136.            .apple+2             'struct'
  2137.      3     .melon.weight+3      'long'
  2138.            .apple+3             'struct'
  2139.      4     .apple.size          'long'
  2140.            .melon.price[0]      'short'
  2141.      5     .apple.size+1        'long'
  2142.            .melon.price[0]+1    'short'
  2143.      6     .melon.price[1]      'short'
  2144.            .apple.size+2        'long'
  2145.      7     .apple.size+3        'long'
  2146.            .melon.price[1]+1    'short'
  2147.      8     .apple.taste         'char'
  2148.            .melon.price[2]      'short'
  2149.      9     .melon.price[2]+1    'short'
  2150.            .apple+9             'struct'
  2151.     10     .apple+10            'struct'
  2152.            .melon+10            'struct'
  2153.     11     .apple+11            'struct'
  2154.            .melon+11            'struct'
  2155.  
  2156. The first member returned is always the I<best> member. The other
  2157. members are sorted according to the rules given above. This means
  2158. that members referenced without an offset are followed by members
  2159. referenced with an offset. Padding regions will be at the end.
  2160.  
  2161. =back
  2162.  
  2163. =head2 dependencies
  2164.  
  2165. =over 8
  2166.  
  2167. =item C<dependencies>
  2168.  
  2169. After some code has been parsed using either
  2170. the L<C<parse>|/"parse"> or L<C<parse_file>|/"parse_file"> methods,
  2171. the L<C<dependencies>|/"dependencies"> method can be used to
  2172. retrieve information about all files that the object
  2173. depends on, i.e. all files that have been parsed.
  2174.  
  2175. The method returns a hash reference. Each key is the
  2176. name of a file, so you could use
  2177.  
  2178.   @files = keys %{$c->dependencies};
  2179.  
  2180. to retrieve a list of these files. The values are
  2181. again hash references, each of which holds the size,
  2182. modification time (mtime), and change time (ctime)
  2183. of the file at the moment it was parsed.
  2184.  
  2185.   use Convert::Binary::C;
  2186.   use Data::Dumper;
  2187.   
  2188.   #----------------------------------------------------------
  2189.   # Create object, set include path, parse 'string.h' header
  2190.   #----------------------------------------------------------
  2191.   my $c = Convert::Binary::C->new
  2192.           ->Include( '/usr/lib/gcc-lib/i686-pc-linux-gnu/3.2.2/include',
  2193.                      '/usr/include' )
  2194.           ->parse_file( 'string.h' );
  2195.   
  2196.   #----------------------------------------------------------
  2197.   # Get dependencies of the object, extract dependency files
  2198.   #----------------------------------------------------------
  2199.   my $depend = $c->dependencies;
  2200.   my @files  = keys %$depend;
  2201.   
  2202.   #-----------------------------
  2203.   # Dump dependencies and files
  2204.   #-----------------------------
  2205.   print Data::Dumper->Dump( [$depend, \@files],
  2206.                          [qw( depend   *files )] );
  2207.  
  2208. The above code would print something like this:
  2209.  
  2210.   $depend = {
  2211.     '/usr/include/features.h' => {
  2212.       'ctime' => 1048627175,
  2213.       'mtime' => 1048627165,
  2214.       'size' => 10999
  2215.     },
  2216.     '/usr/include/sys/cdefs.h' => {
  2217.       'ctime' => 1048627172,
  2218.       'mtime' => 1048627165,
  2219.       'size' => 8400
  2220.     },
  2221.     '/usr/include/gnu/stubs.h' => {
  2222.       'ctime' => 1048627172,
  2223.       'mtime' => 1048627165,
  2224.       'size' => 657
  2225.     },
  2226.     '/usr/include/string.h' => {
  2227.       'ctime' => 1048627175,
  2228.       'mtime' => 1048627165,
  2229.       'size' => 14226
  2230.     },
  2231.     '/usr/lib/gcc-lib/i686-pc-linux-gnu/3.2.2/include/stddef.h' => {
  2232.       'ctime' => 1046205460,
  2233.       'mtime' => 1046205454,
  2234.       'size' => 12695
  2235.     }
  2236.   };
  2237.   @files = (
  2238.     '/usr/include/features.h',
  2239.     '/usr/include/sys/cdefs.h',
  2240.     '/usr/include/gnu/stubs.h',
  2241.     '/usr/include/string.h',
  2242.     '/usr/lib/gcc-lib/i686-pc-linux-gnu/3.2.2/include/stddef.h'
  2243.   );
  2244.  
  2245. =back
  2246.  
  2247. =head2 sourcify
  2248.  
  2249. =over 8
  2250.  
  2251. =item C<sourcify>
  2252.  
  2253. Returns a string that holds the C code necessary to
  2254. represent all parsed C data structures.
  2255.  
  2256.   use Convert::Binary::C;
  2257.   
  2258.   $c = new Convert::Binary::C;
  2259.   $c->parse( <<'END' );
  2260.   
  2261.   #define NUMBER 42
  2262.   
  2263.   typedef struct _mytype mytype;
  2264.   
  2265.   struct _mytype {
  2266.     union {
  2267.       int         iCount;
  2268.       enum count *pCount;
  2269.     } counter;
  2270.   #pragma pack( push, 1 )
  2271.     struct {
  2272.       char string[NUMBER];
  2273.       int  array[NUMBER/sizeof(int)];
  2274.     } storage;
  2275.   #pragma pack( pop )
  2276.     mytype *next;
  2277.   };
  2278.   
  2279.   enum count { ZERO, ONE, TWO, THREE };
  2280.   
  2281.   END
  2282.   
  2283.   print $c->sourcify;
  2284.  
  2285. The above code would print something like this:
  2286.  
  2287.   /* typedef predeclarations */
  2288.   
  2289.   typedef struct _mytype mytype;
  2290.   
  2291.   /* defined enums */
  2292.   
  2293.   #line 20 "[buffer]"
  2294.   enum count
  2295.   {
  2296.       ZERO,
  2297.       ONE,
  2298.       TWO,
  2299.       THREE
  2300.   };
  2301.   
  2302.   
  2303.   /* defined structs and unions */
  2304.   
  2305.   #line 6 "[buffer]"
  2306.   struct _mytype
  2307.   {
  2308.   #line 7 "[buffer]"
  2309.       union
  2310.       {
  2311.           int iCount;
  2312.           enum count *pCount;
  2313.       } counter;
  2314.   #pragma pack( push, 1 )
  2315.   #line 12 "[buffer]"
  2316.       struct
  2317.       {
  2318.           char string[42];
  2319.           int array[10];
  2320.       }
  2321.   #pragma pack( pop )
  2322.       storage;
  2323.       mytype *next;
  2324.   };
  2325.  
  2326. The purpose of the L<C<sourcify>|/"sourcify"> method is to enable some
  2327. kind of platform-independent caching. The C code generated
  2328. by L<C<sourcify>|/"sourcify"> can be parsed by a standard C compiler, as well
  2329. as of course the Convert::Binary::C parser. However, it might
  2330. be significantly shorter than the code that has originally
  2331. been parsed. When parsing a typical header file, it's
  2332. easily possible that you need to open dozens of other files
  2333. that are included from that file, and end up parsing several
  2334. hundred kilobytes of C code. Since most of it is usually
  2335. preprocessor directives, function prototypes and comments,
  2336. the L<C<sourcify>|/"sourcify"> function strips this down to a few kilobytes.
  2337. Saving the L<C<sourcify>|/"sourcify"> string and parsing it next time instead
  2338. of the original code may be a lot faster.
  2339.  
  2340. =back
  2341.  
  2342. The following methods can be used to retrieve information about the
  2343. definitions that have been parsed. The examples given in the description
  2344. for L<C<enum>|/"enum">, L<C<compound>|/"compound"> and L<C<typedef>|/"typedef"> all
  2345. assume this piece of C code has been parsed:
  2346.  
  2347.   typedef unsigned long U32;
  2348.   typedef void *any;
  2349.   
  2350.   enum __socket_type
  2351.   {
  2352.     SOCK_STREAM    = 1,
  2353.     SOCK_DGRAM     = 2,
  2354.     SOCK_RAW       = 3,
  2355.     SOCK_RDM       = 4,
  2356.     SOCK_SEQPACKET = 5,
  2357.     SOCK_PACKET    = 10
  2358.   };
  2359.   
  2360.   struct STRUCT_SV {
  2361.     void *sv_any;
  2362.     U32   sv_refcnt;
  2363.     U32   sv_flags;
  2364.   };
  2365.   
  2366.   typedef union {
  2367.     int abc[2];
  2368.     struct xxx {
  2369.       int a;
  2370.       int b;
  2371.     }   ab[3][4];
  2372.     any ptr;
  2373.   } test;
  2374.  
  2375. =head2 enum_names
  2376.  
  2377. =over 8
  2378.  
  2379. =item C<enum_names>
  2380.  
  2381. Returns a list of identifiers of all defined enumeration
  2382. objects. Enumeration objects don't necessarily have an
  2383. identifier, so something like
  2384.  
  2385.   enum { A, B, C };
  2386.  
  2387. will obviously not appear in the list returned by
  2388. the L<C<enum_names>|/"enum_names"> method. Also, enumerations
  2389. that are not defined within the source code - like in
  2390.  
  2391.   struct foo {
  2392.     enum weekday *pWeekday;
  2393.     unsigned long year;
  2394.   };
  2395.  
  2396. where only a pointer to the C<weekday> enumeration object is used - will
  2397. not be returned, even though they have an identifier. So for the above two
  2398. enumerations, L<C<enum_names>|/"enum_names"> will return an empty list:
  2399.  
  2400.   @names = $c->enum_names;
  2401.  
  2402. The only way to retrieve a list of all enumeration identifiers
  2403. is to use the L<C<enum>|/"enum"> method without additional
  2404. arguments. You can get a list of all enumeration objects
  2405. that have an identifier by using
  2406.  
  2407.   @enums = map { $_->{identifier} || () } $c->enum;
  2408.  
  2409. but these may not have a definition. Thus, the two arrays would
  2410. look like this:
  2411.  
  2412.   @names = ();
  2413.   @enums = ('weekday');
  2414.  
  2415. The L<C<def>|/"def"> method returns a true value for all identifiers returned
  2416. by L<C<enum_names>|/"enum_names">.
  2417.  
  2418. =back
  2419.  
  2420. =head2 enum
  2421.  
  2422. =over 8
  2423.  
  2424. =item enum
  2425.  
  2426. =item C<enum> LIST
  2427.  
  2428. Returns a list of references to hashes containing
  2429. detailed information about all enumerations that
  2430. have been parsed.
  2431.  
  2432. If a list of enumeration identifiers is passed to the
  2433. method, the returned list will only contain hash
  2434. references for those enumerations. The enumeration
  2435. identifiers may optionally be prefixed by C<enum>.
  2436.  
  2437. If an enumeration identifier cannot be found, a
  2438. warning is issued and the returned list will contain
  2439. an undefined value at that position.
  2440.  
  2441. In scalar context, the number of enumerations will
  2442. be returned as long as the number of arguments to
  2443. the method call is not 1. In the latter case, a
  2444. hash reference holding information for the enumeration
  2445. will be returned.
  2446.  
  2447. The list returned by the L<C<enum>|/"enum"> method looks
  2448. similar to this:
  2449.  
  2450.   @enum = (
  2451.     {
  2452.       'enumerators' => {
  2453.         'SOCK_STREAM' => 1,
  2454.         'SOCK_RAW' => 3,
  2455.         'SOCK_SEQPACKET' => 5,
  2456.         'SOCK_RDM' => 4,
  2457.         'SOCK_PACKET' => 10,
  2458.         'SOCK_DGRAM' => 2
  2459.       },
  2460.       'identifier' => '__socket_type',
  2461.       'context' => 'definitions.c(4)',
  2462.       'sign' => 0
  2463.     }
  2464.   );
  2465.  
  2466. =over 4
  2467.  
  2468. =item C<identifier>
  2469.  
  2470. holds the enumeration identifier. This key is not
  2471. present if the enumeration has no identifier.
  2472.  
  2473. =item C<context>
  2474.  
  2475. is the context in which the enumeration is defined. This
  2476. is the filename followed by the line number in parentheses.
  2477.  
  2478. =item C<enumerators>
  2479.  
  2480. is a reference to a hash table that holds
  2481. all enumerators of the enumeration.
  2482.  
  2483. =item C<sign>
  2484.  
  2485. is a boolean indicating if the enumeration is
  2486. signed (i.e. has negative values).
  2487.  
  2488. =back
  2489.  
  2490. One useful application may be to create a hash table that
  2491. holds all enumerators of all defined enumerations:
  2492.  
  2493.   %enum = map %{ $_->{enumerators} || {} }, $c->enum;
  2494.  
  2495. The C<%enum> hash table would then be:
  2496.  
  2497.   %enum = (
  2498.     'SOCK_STREAM' => 1,
  2499.     'SOCK_RAW' => 3,
  2500.     'SOCK_SEQPACKET' => 5,
  2501.     'SOCK_RDM' => 4,
  2502.     'SOCK_DGRAM' => 2,
  2503.     'SOCK_PACKET' => 10
  2504.   );
  2505.  
  2506. =back
  2507.  
  2508. =head2 compound_names
  2509.  
  2510. =over 8
  2511.  
  2512. =item C<compound_names>
  2513.  
  2514. Returns a list of identifiers of all structs and unions
  2515. (compound data structures) that are defined in the parsed
  2516. source code. Like enumerations, compounds don't need to
  2517. have an identifier, nor do they need to be defined.
  2518.  
  2519. Again, the only way to retrieve information about all
  2520. struct and union objects is to use the L<C<compound>|/"compound"> method
  2521. and don't pass it any arguments. If you should need a
  2522. list of all struct and union identifiers, you can use:
  2523.  
  2524.   @compound = map { $_->{identifier} || () } $c->compound;
  2525.  
  2526. The L<C<def>|/"def"> method returns a true value for all identifiers returned
  2527. by L<C<compound_names>|"compound_names">.
  2528.  
  2529. If you need the names of only the structs or only the unions, use
  2530. the L<C<struct_names>|/"struct_names"> and L<C<union_names>|/"union_names"> methods
  2531. respectively.
  2532.  
  2533. =back
  2534.  
  2535. =head2 compound
  2536.  
  2537. =over 8
  2538.  
  2539. =item C<compound>
  2540.  
  2541. =item C<compound> LIST
  2542.  
  2543. Returns a list of references to hashes containing
  2544. detailed information about all compounds (structs and
  2545. unions) that have been parsed.
  2546.  
  2547. If a list of struct/union identifiers is passed to the
  2548. method, the returned list will only contain hash
  2549. references for those compounds. The identifiers may
  2550. optionally be prefixed by C<struct> or C<union>,
  2551. which limits the search to the specified kind of
  2552. compound.
  2553.  
  2554. If an identifier cannot be found, a warning is issued
  2555. and the returned list will contain an undefined value
  2556. at that position.
  2557.  
  2558. In scalar context, the number of compounds will
  2559. be returned as long as the number of arguments to
  2560. the method call is not 1. In the latter case, a
  2561. hash reference holding information for the compound
  2562. will be returned.
  2563.  
  2564. The list returned by the L<C<compound>|/"compound"> method looks similar
  2565. to this:
  2566.  
  2567.   @compound = (
  2568.     {
  2569.       'identifier' => 'STRUCT_SV',
  2570.       'align' => 1,
  2571.       'context' => 'definitions.c(14)',
  2572.       'pack' => 0,
  2573.       'type' => 'struct',
  2574.       'declarations' => [
  2575.         {
  2576.           'declarators' => [
  2577.             {
  2578.               'declarator' => '*sv_any',
  2579.               'size' => 4,
  2580.               'offset' => 0
  2581.             }
  2582.           ],
  2583.           'type' => 'void'
  2584.         },
  2585.         {
  2586.           'declarators' => [
  2587.             {
  2588.               'declarator' => 'sv_refcnt',
  2589.               'size' => 4,
  2590.               'offset' => 4
  2591.             }
  2592.           ],
  2593.           'type' => 'U32'
  2594.         },
  2595.         {
  2596.           'declarators' => [
  2597.             {
  2598.               'declarator' => 'sv_flags',
  2599.               'size' => 4,
  2600.               'offset' => 8
  2601.             }
  2602.           ],
  2603.           'type' => 'U32'
  2604.         }
  2605.       ],
  2606.       'size' => 12
  2607.     },
  2608.     {
  2609.       'identifier' => 'xxx',
  2610.       'align' => 1,
  2611.       'context' => 'definitions.c(22)',
  2612.       'pack' => 0,
  2613.       'type' => 'struct',
  2614.       'declarations' => [
  2615.         {
  2616.           'declarators' => [
  2617.             {
  2618.               'declarator' => 'a',
  2619.               'size' => 4,
  2620.               'offset' => 0
  2621.             }
  2622.           ],
  2623.           'type' => 'int'
  2624.         },
  2625.         {
  2626.           'declarators' => [
  2627.             {
  2628.               'declarator' => 'b',
  2629.               'size' => 4,
  2630.               'offset' => 4
  2631.             }
  2632.           ],
  2633.           'type' => 'int'
  2634.         }
  2635.       ],
  2636.       'size' => 8
  2637.     },
  2638.     {
  2639.       'align' => 1,
  2640.       'context' => 'definitions.c(20)',
  2641.       'pack' => 0,
  2642.       'type' => 'union',
  2643.       'declarations' => [
  2644.         {
  2645.           'declarators' => [
  2646.             {
  2647.               'declarator' => 'abc[2]',
  2648.               'size' => 8,
  2649.               'offset' => 0
  2650.             }
  2651.           ],
  2652.           'type' => 'int'
  2653.         },
  2654.         {
  2655.           'declarators' => [
  2656.             {
  2657.               'declarator' => 'ab[3][4]',
  2658.               'size' => 96,
  2659.               'offset' => 0
  2660.             }
  2661.           ],
  2662.           'type' => 'struct xxx'
  2663.         },
  2664.         {
  2665.           'declarators' => [
  2666.             {
  2667.               'declarator' => 'ptr',
  2668.               'size' => 4,
  2669.               'offset' => 0
  2670.             }
  2671.           ],
  2672.           'type' => 'any'
  2673.         }
  2674.       ],
  2675.       'size' => 96
  2676.     }
  2677.   );
  2678.  
  2679. =over 4
  2680.  
  2681. =item C<identifier>
  2682.  
  2683. holds the struct or union identifier. This
  2684. key is not present if the compound has no identifier.
  2685.  
  2686. =item C<context>
  2687.  
  2688. is the context in which the struct or union is defined. This
  2689. is the filename followed by the line number in parentheses.
  2690.  
  2691. =item C<type>
  2692.  
  2693. is either 'struct' or 'union'.
  2694.  
  2695. =item C<size>
  2696.  
  2697. is the size of the struct or union.
  2698.  
  2699. =item C<align>
  2700.  
  2701. is the alignment of the struct or union.
  2702.  
  2703. =item C<pack>
  2704.  
  2705. is the struct member alignment if the compound
  2706. is packed, or zero otherwise.
  2707.  
  2708. =item C<declarations>
  2709.  
  2710. is an array of hash references describing each struct
  2711. declaration:
  2712.  
  2713. =over 4
  2714.  
  2715. =item C<type>
  2716.  
  2717. is the type of the struct declaration. This may be a
  2718. string or a reference to a hash describing the type.
  2719.  
  2720. =item C<declarators>
  2721.  
  2722. is an array of hashes describing each declarator:
  2723.  
  2724. =over 4
  2725.  
  2726. =item C<declarator>
  2727.  
  2728. is a string representation of the declarator.
  2729.  
  2730. =item C<offset>
  2731.  
  2732. is the offset of the struct member represented by
  2733. the current declarator relative to the beginning
  2734. of the struct or union.
  2735.  
  2736. =item C<size>
  2737.  
  2738. is the size occupied by the struct member represented
  2739. by the current declarator.
  2740.  
  2741. =back
  2742.  
  2743. =back
  2744.  
  2745. =back
  2746.  
  2747. It may be useful to have separate lists for structs and
  2748. unions. One way to retrieve such lists would be to use
  2749.  
  2750.   push @{$_->{type} eq 'union' ? \@unions : \@structs}, $_
  2751.       for $c->compound;
  2752.  
  2753. However, you should use the L<C<struct>|/"struct"> and L<C<union>|/"union"> methods,
  2754. which is a lot simpler:
  2755.  
  2756.   @structs = $c->struct;
  2757.   @unions  = $c->union;
  2758.  
  2759. =back
  2760.  
  2761. =head2 struct_names
  2762.  
  2763. =over 8
  2764.  
  2765. =item C<struct_names>
  2766.  
  2767. Returns a list of all defined struct identifiers.
  2768. This is equivalent to calling L<C<compound_names>|"compound_names">, just
  2769. that it only returns the names of the struct identifiers and
  2770. doesn't return the names of the union identifiers.
  2771.  
  2772. =back
  2773.  
  2774. =head2 struct
  2775.  
  2776. =over 8
  2777.  
  2778. =item C<struct>
  2779.  
  2780. =item C<struct> LIST
  2781.  
  2782. Like the L<C<compound>|/"compound"> method, but only allows for structs.
  2783.  
  2784. =back
  2785.  
  2786. =head2 union_names
  2787.  
  2788. =over 8
  2789.  
  2790. =item C<union_names>
  2791.  
  2792. Returns a list of all defined union identifiers.
  2793. This is equivalent to calling L<C<compound_names>|"compound_names">, just
  2794. that it only returns the names of the union identifiers and
  2795. doesn't return the names of the struct identifiers.
  2796.  
  2797. =back
  2798.  
  2799. =head2 union
  2800.  
  2801. =over 8
  2802.  
  2803. =item C<union>
  2804.  
  2805. =item C<union> LIST
  2806.  
  2807. Like the L<C<compound>|/"compound"> method, but only allows for unions.
  2808.  
  2809. =back
  2810.  
  2811. =head2 typedef_names
  2812.  
  2813. =over 8
  2814.  
  2815. =item C<typedef_names>
  2816.  
  2817. Returns a list of all defined typedef identifiers. Typedefs
  2818. that do not specify a type that you could actually work with
  2819. will not be returned.
  2820.  
  2821. The L<C<def>|/"def"> method returns a true value for all identifiers returned
  2822. by L<C<typedef_names>|/"typedef_names">.
  2823.  
  2824. =back
  2825.  
  2826. =head2 typedef
  2827.  
  2828. =over 8
  2829.  
  2830. =item C<typedef>
  2831.  
  2832. =item C<typedef> LIST
  2833.  
  2834. Returns a list of references to hashes containing
  2835. detailed information about all typedefs that have
  2836. been parsed.
  2837.  
  2838. If a list of typedef identifiers is passed to the
  2839. method, the returned list will only contain hash
  2840. references for those typedefs.
  2841.  
  2842. If an identifier cannot be found, a warning is issued
  2843. and the returned list will contain an undefined value
  2844. at that position.
  2845.  
  2846. In scalar context, the number of typedefs will
  2847. be returned as long as the number of arguments to
  2848. the method call is not 1. In the latter case, a
  2849. hash reference holding information for the typedef
  2850. will be returned.
  2851.  
  2852. The list returned by the L<C<typedef>|/"typedef"> method looks similar
  2853. to this:
  2854.  
  2855.   @typedef = (
  2856.     {
  2857.       'declarator' => 'U32',
  2858.       'type' => 'unsigned long'
  2859.     },
  2860.     {
  2861.       'declarator' => '*any',
  2862.       'type' => 'void'
  2863.     },
  2864.     {
  2865.       'declarator' => 'test',
  2866.       'type' => {
  2867.         'align' => 1,
  2868.         'context' => 'definitions.c(20)',
  2869.         'pack' => 0,
  2870.         'type' => 'union',
  2871.         'declarations' => [
  2872.           {
  2873.             'declarators' => [
  2874.               {
  2875.                 'declarator' => 'abc[2]',
  2876.                 'size' => 8,
  2877.                 'offset' => 0
  2878.               }
  2879.             ],
  2880.             'type' => 'int'
  2881.           },
  2882.           {
  2883.             'declarators' => [
  2884.               {
  2885.                 'declarator' => 'ab[3][4]',
  2886.                 'size' => 96,
  2887.                 'offset' => 0
  2888.               }
  2889.             ],
  2890.             'type' => 'struct xxx'
  2891.           },
  2892.           {
  2893.             'declarators' => [
  2894.               {
  2895.                 'declarator' => 'ptr',
  2896.                 'size' => 4,
  2897.                 'offset' => 0
  2898.               }
  2899.             ],
  2900.             'type' => 'any'
  2901.           }
  2902.         ],
  2903.         'size' => 96
  2904.       }
  2905.     }
  2906.   );
  2907.  
  2908. =over 4
  2909.  
  2910. =item C<declarator>
  2911.  
  2912. is the type declarator.
  2913.  
  2914. =item C<type>
  2915.  
  2916. is the type specification. This may be a string
  2917. or a reference to a hash describing the type.
  2918. See L<C<enum>|/"enum"> and L<C<compound>|/"compound"> for
  2919. a description on how to interpret this hash.
  2920.  
  2921. =back
  2922.  
  2923. =back
  2924.  
  2925. =head1 FUNCTIONS
  2926.  
  2927. =head2 Convert::Binary::C::feature
  2928.  
  2929. =over 8
  2930.  
  2931. =item C<feature> STRING
  2932.  
  2933. Checks if Convert::Binary::C was built with certain features.
  2934. For example,
  2935.  
  2936.   print "debugging version"
  2937.       if Convert::Binary::C::feature( 'debug' );
  2938.  
  2939. will check if Convert::Binary::C was built with debugging support
  2940. enabled. The C<feature> function returns C<1> if the feature is
  2941. enabled, C<0> if the feature is disabled, and C<undef> if the
  2942. feature is unknown. Currently the only features that can be checked
  2943. are C<debug> and C<threads>.
  2944.  
  2945. You can enable or disable certain features at compile time of the
  2946. module by using the
  2947.  
  2948.   perl Makefile.PL enable-feature disable-feature
  2949.  
  2950. syntax.
  2951.  
  2952. =back
  2953.  
  2954. =head1 DEBUGGING
  2955.  
  2956. Like perl itself, Convert::Binary::C can be compiled with debugging
  2957. support that can then be selectively enabled at runtime. You can
  2958. specify whether you like to build Convert::Binary::C with debugging
  2959. support or not by explicitly giving an argument to F<Makefile.PL>.
  2960. Use
  2961.  
  2962.   perl Makefile.PL enable-debug
  2963.  
  2964. to enable debugging, or
  2965.  
  2966.   perl Makefile.PL disable-debug
  2967.  
  2968. to disable debugging. The default will depend on how your perl
  2969. binary was built. If it was built with C<-DDEBUGGING>,
  2970. Convert::Binary::C will be built with debugging support, too.
  2971.  
  2972. Once you have built Convert::Binary::C with debugging support, you
  2973. can use the following syntax to enable debug output. Instead of
  2974.  
  2975.   use Convert::Binary::C;
  2976.  
  2977. you simply say
  2978.  
  2979.   use Convert::Binary::C debug => 'all';
  2980.  
  2981. which will enable all debug output. However, I don't recommend
  2982. to enable all debug output, because that can be a fairly large
  2983. amount.
  2984.  
  2985. =head2 Debugging options
  2986.  
  2987. Instead of saying C<all>, you can pass a string that
  2988. consists of one or more of the following characters:
  2989.  
  2990.   m   enable memory allocation tracing
  2991.   M   enable memory allocation & assertion tracing
  2992.   
  2993.   h   enable hash table debugging
  2994.   H   enable hash table dumps
  2995.   
  2996.   d   enable debug output from the XS module
  2997.   c   enable debug output from the ctlib
  2998.   t   enable debug output about type objects
  2999.   
  3000.   l   enable debug output from the C lexer
  3001.   p   enable debug output from the C parser
  3002.   r   enable debug output from the #pragma parser
  3003.   
  3004.   y   enable debug output from yacc (bison)
  3005.  
  3006. So the following might give you a brief overview of what's
  3007. going on inside Convert::Binary::C:
  3008.  
  3009.   use Convert::Binary::C debug => 'dct';
  3010.  
  3011. When you want to debug memory allocation using
  3012.  
  3013.   use Convert::Binary::C debug => 'm';
  3014.  
  3015. you can use the Perl script F<check_alloc.pl> that resides
  3016. in the F<ctlib/util/tool> directory to extract statistics
  3017. about memory usage and information about memory leaks from
  3018. the resulting debug output.
  3019.  
  3020. =head2 Redirecting debug output
  3021.  
  3022. By default, all debug output is written to C<stderr>. You
  3023. can, however, redirect the debug output to a file with
  3024. the C<debugfile> option:
  3025.  
  3026.   use Convert::Binary::C debug     => 'dcthHm',
  3027.                          debugfile => './debug.out';
  3028.  
  3029. If the file cannot be opened, you'll receive a warning and
  3030. the output will go the C<stderr> way again.
  3031.  
  3032. Alternatively, you can use the environment
  3033. variables L<C<CBC_DEBUG_OPT>|/"CBC_DEBUG_OPT"> and L<C<CBC_DEBUG_FILE>|/"CBC_DEBUG_FILE"> to
  3034. turn on debug output.
  3035.  
  3036. If Convert::Binary::C is built without debugging support,
  3037. passing the C<debug> or C<debugfile> options will cause
  3038. a warning to be issued. The corresponding environment
  3039. variables will simply be ignored.
  3040.  
  3041. =head1 ENVIRONMENT
  3042.  
  3043. =head2 C<CBC_DEBUG_OPT>
  3044.  
  3045. If Convert::Binary::C is built with debugging
  3046. support, you can use this variable to specify
  3047. the L<debugging options|/"Debugging options">.
  3048.  
  3049. =head2 C<CBC_DEBUG_FILE>
  3050.  
  3051. If Convert::Binary::C is built with debugging support,
  3052. you can use this variable to L<redirect|/"Redirecting debug output"> the
  3053. debug output to a file.
  3054.  
  3055. =head2 C<CBC_DISABLE_PARSER>
  3056.  
  3057. This variable is intended purely for development. Setting
  3058. it to a non-zero value disables the Convert::Binary::C parser,
  3059. which means that no information is collected from the file
  3060. or code that is parsed. However, the preprocessor will run,
  3061. which is useful for benchmarking the preprocessor.
  3062.  
  3063. =head1 BITFIELDS
  3064.  
  3065. Bitfields are currently not supported by Convert::Binary::C,
  3066. because I generally don't use them. I plan to support them
  3067. in a later release, when I will have found an easy way of integrating
  3068. them into the module.
  3069.  
  3070. Whenever a method has to deal with bitfields, it will issue
  3071. a warning message that bitfields are unsupported. Thus, you
  3072. may use bitfields in your C source code, but you won't be
  3073. annoyed with warning messages unless you really use a type
  3074. that actually contains bitfields in a method call
  3075. like L<C<sizeof>|/"sizeof"> or L<C<pack>|/"pack">.
  3076.  
  3077. While bitfields are not appropriately handled by the conversion
  3078. routines yet, they are already parsed correctly. This means
  3079. that you can reliably use the declarator fields as returned
  3080. by the L<C<struct>|/"struct"> or L<C<typedef>|/"typedef"> methods.
  3081. Given the following source
  3082.  
  3083.   struct bitfield {
  3084.     int seven:7;
  3085.     int :1;
  3086.     int four:4, :0;
  3087.     int integer;
  3088.   };
  3089.  
  3090. a call to L<C<struct>|/"struct"> will return
  3091.  
  3092.   @struct = (
  3093.     {
  3094.       'identifier' => 'bitfield',
  3095.       'align' => 1,
  3096.       'context' => 'bitfields.c(1)',
  3097.       'pack' => 0,
  3098.       'type' => 'struct',
  3099.       'declarations' => [
  3100.         {
  3101.           'declarators' => [
  3102.             {
  3103.               'declarator' => 'seven:7'
  3104.             }
  3105.           ],
  3106.           'type' => 'int'
  3107.         },
  3108.         {
  3109.           'declarators' => [
  3110.             {
  3111.               'declarator' => ':1'
  3112.             }
  3113.           ],
  3114.           'type' => 'int'
  3115.         },
  3116.         {
  3117.           'declarators' => [
  3118.             {
  3119.               'declarator' => 'four:4'
  3120.             },
  3121.             {
  3122.               'declarator' => ':0'
  3123.             }
  3124.           ],
  3125.           'type' => 'int'
  3126.         },
  3127.         {
  3128.           'declarators' => [
  3129.             {
  3130.               'declarator' => 'integer',
  3131.               'size' => 4,
  3132.               'offset' => 0
  3133.             }
  3134.           ],
  3135.           'type' => 'int'
  3136.         }
  3137.       ],
  3138.       'size' => 4
  3139.     }
  3140.   );
  3141.  
  3142. No size/offset keys will be returned for bitfield entries.
  3143. Also, the size of a structure containing bitfields is not
  3144. valid, as bitfields internally do not increase the size
  3145. of a structure yet.
  3146.  
  3147. =head1 MULTITHREADING
  3148.  
  3149. Convert::Binary::C was designed to be thread-safe.
  3150.  
  3151. Since the used preprocessor unfortunately isn't
  3152. re-entrant, source code parsing using
  3153. the L<C<parse>|/"parse"> and L<C<parse_file>|/"parse_file"> methods
  3154. is locked, so don't expect these routines to run in parallel
  3155. on multithreaded perls.
  3156.  
  3157. =head1 CREDITS
  3158.  
  3159. =over 2
  3160.  
  3161. =item *
  3162.  
  3163. My love Jennifer for always being there, for filling my life with
  3164. joy and last but not least for proofreading the documentation.
  3165.  
  3166. =item *
  3167.  
  3168. Alain Barbet E<lt>alian@cpan.orgE<gt> for testing and debugging
  3169. support.
  3170.  
  3171. =item *
  3172.  
  3173. Michael J. Hohmann E<lt>mjh@scientist.deE<gt> for endless discussions
  3174. on our way to and back home from work, and for making me think
  3175. about supporting L<C<pack>|/"pack"> and L<C<unpack>|/"unpack"> for
  3176. compound members.
  3177.  
  3178. =item *
  3179.  
  3180. Thorsten Jens E<lt>thojens@gmx.deE<gt> for testing the package
  3181. on various platforms.
  3182.  
  3183. =item *
  3184.  
  3185. Mark Overmeer E<lt>mark@overmeer.netE<gt> for suggesting the
  3186. module name and giving invaluable feedback.
  3187.  
  3188. =item *
  3189.  
  3190. Thomas Pornin E<lt>pornin@bolet.orgE<gt> for his
  3191. excellent C<ucpp> preprocessor library.
  3192.  
  3193. =item *
  3194.  
  3195. Marc Rosenthal for his suggestions and support.
  3196.  
  3197. =item *
  3198.  
  3199. James Roskind, as his C parser was a great starting point to fix
  3200. all the problems I had with my original parser based only on the
  3201. ANSI ruleset.
  3202.  
  3203. =item *
  3204.  
  3205. Gisbert W. Selke for spotting some interesting bugs and providing
  3206. extensive reports.
  3207.  
  3208. =item *
  3209.  
  3210. Steffen Zimmermann for a prolific discussion on the cloning
  3211. algorithm.
  3212.  
  3213. =back
  3214.  
  3215. =head1 BUGS
  3216.  
  3217. I'm sure there are still lots of bugs in the code for this
  3218. module. If you find any bugs, Convert::Binary::C doesn't
  3219. seem to build on your system or any of its tests fail, please
  3220. send a mail to E<lt>mhx@cpan.orgE<gt>.
  3221.  
  3222. =head1 TODO
  3223.  
  3224. If you're interested in what I currently plan to improve
  3225. (or fix), have a look at the F<TODO> file.
  3226.  
  3227. =head1 POSTCARDS
  3228.  
  3229. If you're using my module and like it, you can show your appreciation
  3230. by sending me a postcard from where you live. I won't urge you to do it,
  3231. it's completely up to you. To me, this is just a very nice way of
  3232. receiving feedback about my work. Please send your postcard to:
  3233.  
  3234.   Marcus Holland-Moritz
  3235.   Kuppinger Weg 28
  3236.   71116 Gaertringen
  3237.   GERMANY
  3238.  
  3239. =head1 COPYRIGHT
  3240.  
  3241. Copyright (c) 2002-2003 Marcus Holland-Moritz. All rights reserved.
  3242. This program is free software; you can redistribute it and/or modify
  3243. it under the same terms as Perl itself.
  3244.  
  3245. The C<ucpp> library is (c) 1998-2002 Thomas Pornin. For licence
  3246. and redistribution details refer to F<ctlib/ucpp/README>.
  3247.  
  3248. Portions copyright (c) 1989, 1990 James A. Roskind.
  3249.  
  3250. The include files located in F<t/include/include>, which are used
  3251. in some of the test scripts are (c) 1991-1999, 2000, 2001 Free Software
  3252. Foundation, Inc. They are neither required to create the binary nor
  3253. linked to the source code of this module in any other way.
  3254.  
  3255. =head1 SEE ALSO
  3256.  
  3257. See L<ccconfig>, L<perl>, L<perldata>, L<perlop>, L<perlvar> and L<Data::Dumper>.
  3258.  
  3259. =cut
  3260.  
  3261.