Debian Codegraph @

examples/time.pl

raw
1 use strict;
2 use warnings;
3 use Convert::Binary::C;
4 use FFI::Platypus 2.00;
5 use Data::Dumper qw( Dumper );
6
7 my $c = Convert::Binary::C->new;
8
9 # Alignment of zero (0) means use
10 # the alignment of your CPU
11 $c->configure( Alignment => 0 );
12
13 # parse the tm record structure so
14 # that Convert::Binary::C knows
15 # what to spit out and suck in
16 $c->parse(<<ENDC);
17 struct tm {
18 int tm_sec;
19 int tm_min;
20 int tm_hour;
21 int tm_mday;
22 int tm_mon;
23 int tm_year;
24 int tm_wday;
25 int tm_yday;
26 int tm_isdst;
27 long int tm_gmtoff;
28 const char *tm_zone;
29 };
30 ENDC
31
32 # get the size of tm so that we can give it
33 # to Platypus
34 my $tm_size = $c->sizeof("tm");
35
36 # create the Platypus instance and create the appropriate
37 # types and functions
38 my $ffi = FFI::Platypus->new( api => 2 );
39 $ffi->lib(undef);
40 $ffi->type("record($tm_size)*" => 'tm');
41 $ffi->attach( [ localtime => 'my_localtime' ] => ['time_t*'] => 'tm' );
42 $ffi->attach( [ time => 'my_time' ] => ['tm'] => 'time_t' );
43
44 # ===============================================
45 # get the tm struct from the C localtime function
46 # note that we pass in a reference to the value that time
47 # returns because localtime takes a pointer to time_t
48 # for some reason.
49 my $time_hashref = $c->unpack( tm => my_localtime(\time) );
50
51 # tm_zone comes back from Convert::Binary::C as an opaque,
52 # cast it into a string. We localize it to just this do
53 # block so that it will be a pointer when we pass it back
54 # to C land below.
55 do {
56 local $time_hashref->{tm_zone} = $ffi->cast(opaque => string => $time_hashref->{tm_zone});
57 print Dumper($time_hashref);
58 };
59
60 # ===============================================
61 # convert the tm struct back into an epoch value
62 my $time = my_time( $c->pack( tm => $time_hashref ) );
63
64 print "time = $time\n";
65 print "perl time = ", time, "\n";