| 1 | package | ||
| 2 | Archive::Libarchive::FFI::SweetLite; | ||
| 3 | |||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use FFI::Raw; | ||
| 7 | use Text::ParseWords qw( shellwords ); | ||
| 8 | use Exporter::Tidy | ||
| 9 | default => [qw( | ||
| 10 | ffi_lib attach_function | ||
| 11 | _void _int _uint _long _ulong _int64 _uint64 | ||
| 12 | _short _ushort _char _uchar _float _double _str _ptr | ||
| 13 | )]; | ||
| 14 | |||
| 15 | # This is intended for use with Archive::Libarchive::FFI ONLY until | ||
| 16 | # FFI::Sweet makes it to CPAN | ||
| 17 | |||
| 18 | my @libs; | ||
| 19 | |||
| 20 | sub ffi_lib ($) | ||
| 21 | { | ||
| 22 | my $lib = shift; | ||
| 23 | push @libs, $$lib; | ||
| 24 | } | ||
| 25 | |||
| 26 | sub attach_function ($$$;$) | ||
| 27 | { | ||
| 28 | my($name, $arg_types, $rv_type, $wrapper ) = @_; | ||
| 29 | my $pkg = caller; | ||
| 30 | $arg_types = [] unless defined $arg_types; | ||
| 31 | my $install_name = $name; | ||
| 32 | ( $name, $install_name ) = @{ $name } if ref $name; | ||
| 33 | |||
| 34 | foreach my $lib (@libs) | ||
| 35 | { | ||
| 36 | my $ffi = eval { FFI::Raw->new($lib, $name, $rv_type, @$arg_types) }; | ||
| 37 | next if $@; | ||
| 38 | |||
| 39 | my $base_sub = sub { | ||
| 40 | my @args = @_; | ||
| 41 | my $ret = eval { | ||
| 42 | $ffi->call(@args); | ||
| 43 | }; | ||
| 44 | die "$name: $@" if $@; | ||
| 45 | return $ret; | ||
| 46 | }; | ||
| 47 | |||
| 48 | no strict 'refs'; | ||
| 49 | *{join '::', $pkg, $install_name} = $wrapper ? sub { $wrapper->($base_sub, @_) } : $base_sub; | ||
| 50 | return; | ||
| 51 | } | ||
| 52 | |||
| 53 | die "unable to find $name\n"; | ||
| 54 | } | ||
| 55 | |||
| 56 | foreach my $type (qw( void int uint long ulong int64 uint64 short ushort char uchar float double str ptr )) | ||
| 57 | { | ||
| 58 | no strict 'refs'; | ||
| 59 | eval qq{ sub _$type { FFI::Raw::$type\() } }; | ||
| 60 | die $@ if $@; | ||
| 61 | } | ||
| 62 | |||
| 63 | 1; | ||
| 64 | |||
| 65 | __END__ |