1package FFI::Platypus; 2 3use strict; 4use warnings; 5use 5.008004; 6use Carp qw( croak ); 7use FFI::Platypus::Function; 8use FFI::Platypus::Type; 9 10# ABSTRACT: Write Perl bindings to non-Perl libraries with FFI. No XS required. 11our $VERSION = '1.56'; # VERSION 12 13# Platypus-Man, 14# Platypus-Man, 15# Does Whatever A Platypus Can 16# Is Mildly Venomous 17# Hangs Out In Rivers By Caves 18# Look Out! 19# Here Comes The Platypus-Man 20 21# From the original FFI::Platypus prototype: 22# Kinda like gluing a duckbill to an adorable mammal 23 24 25our @CARP_NOT = qw( FFI::Platypus::Declare FFI::Platypus::Record ); 26 27require XSLoader; 28XSLoader::load( 29 'FFI::Platypus', $FFI::Platypus::VERSION || 0 30); 31 32 33sub new 34{ 35 my($class, %args) = @_; 36 my @lib; 37 if(exists $args{lib}) 38 { 39 if(!ref($args{lib})) 40 { 41 push @lib, $args{lib}; 42 } 43 elsif(ref($args{lib}) eq 'ARRAY') 44 { 45 push @lib, @{$args{lib}}; 46 } 47 else 48 { 49 croak "lib argument must be a scalar or array reference"; 50 } 51 } 52 53 my $api = $args{api} || 0; 54 my $experimental = $args{experimental} || 0; 55 56 if($experimental == 1) 57 { 58 Carp::croak("Please do not use the experimental version of api = 1, instead require FFI::Platypus 1.00 or better"); 59 } 60 61 if(defined $api && $api > 1 && $experimental != $api) 62 { 63 Carp::cluck("Enabling development API version $api prior to FFI::Platypus $api.00"); 64 } 65 66 my $tp; 67 68 if($api == 0) 69 { 70 $tp = 'Version0'; 71 } 72 elsif($api == 1) 73 { 74 $tp = 'Version1'; 75 } 76 elsif($api == 2) 77 { 78 $tp = 'Version1'; 79 } 80 else 81 { 82 Carp::croak("API version $api not (yet) implemented"); 83 } 84 85 require "FFI/Platypus/TypeParser/$tp.pm"; 86 $tp = "FFI::Platypus::TypeParser::$tp"; 87 88 my $self = bless { 89 lib => \@lib, 90 lang => '', 91 handles => {}, 92 abi => -1, 93 api => $api, 94 tp => $tp->new, 95 fini => [], 96 ignore_not_found => defined $args{ignore_not_found} ? $args{ignore_not_found} : 0, 97 }, $class; 98 99 $self->lang($args{lang} || 'C'); 100 101 $self; 102} 103 104sub _lang_class ($) 105{ 106 my($lang) = @_; 107 my $class = $lang =~ m/^=(.*)$/ ? $1 : "FFI::Platypus::Lang::$lang"; 108 unless($class->can('native_type_map')) 109 { 110 my $pm = "$class.pm"; 111 $pm =~ s/::/\//g; 112 require $pm; 113 } 114 croak "$class does not provide native_type_map method" 115 unless $class->can("native_type_map"); 116 $class; 117} 118 119 120sub lib 121{ 122 my($self, @new) = @_; 123 124 if(@new) 125 { 126 push @{ $self->{lib} }, map { ref $_ eq 'CODE' ? $_->() : $_ } @new; 127 delete $self->{mangler}; 128 } 129 130 @{ $self->{lib} }; 131} 132 133 134sub ignore_not_found 135{ 136 my($self, $value) = @_; 137 138 if(defined $value) 139 { 140 $self->{ignore_not_found} = $value; 141 } 142 143 $self->{ignore_not_found}; 144} 145 146 147sub lang 148{ 149 my($self, $value) = @_; 150 151 if(defined $value && $value ne $self->{lang}) 152 { 153 $self->{lang} = $value; 154 my $class = _lang_class($self->{lang}); 155 $self->abi($class->abi) if $class->can('abi'); 156 157 { 158 my %type_map; 159 my $map = $class->native_type_map( 160 $self->{api} > 0 161 ? (api => $self->{api}) 162 : () 163 ); 164 foreach my $key (keys %$map) 165 { 166 my $value = $map->{$key}; 167 next unless $self->{tp}->have_type($value); 168 $type_map{$key} = $value; 169 } 170 $type_map{$_} = $_ for grep { $self->{tp}->have_type($_) } 171 qw( void sint8 uint8 sint16 uint16 sint32 uint32 sint64 uint64 float double string opaque 172 longdouble complex_float complex_double ); 173 $type_map{pointer} = 'opaque' if $self->{tp}->isa('FFI::Platypus::TypeParser::Version0'); 174 $self->{tp}->type_map(\%type_map); 175 } 176 177 $class->load_custom_types($self) if $class->can('load_custom_types'); 178 } 179 180 $self->{lang}; 181} 182 183 184sub api { shift->{api} } 185 186 187sub type 188{ 189 my($self, $name, $alias) = @_; 190 croak "usage: \$ffi->type(name => alias) (alias is optional)" unless defined $self && defined $name; 191 192 $self->{tp}->check_alias($alias) if defined $alias; 193 my $type = $self->{tp}->parse($name); 194 $self->{tp}->set_alias($alias, $type) if defined $alias; 195 196 $self; 197} 198 199 200sub custom_type 201{ 202 my($self, $alias, $cb) = @_; 203 204 my $argument_count = $cb->{argument_count} || 1; 205 206 croak "argument_count must be >= 1" 207 unless $argument_count >= 1; 208 209 croak "Usage: \$ffi->custom_type(\$alias, { ... })" 210 unless defined $alias && ref($cb) eq 'HASH'; 211 212 croak "must define at least one of native_to_perl, perl_to_native, or perl_to_native_post" 213 unless defined $cb->{native_to_perl} || defined $cb->{perl_to_native} || defined $cb->{perl_to_native_post}; 214 215 $self->{tp}->check_alias($alias); 216 217 my $type = $self->{tp}->create_type_custom( 218 $cb->{native_type}, 219 $cb->{perl_to_native}, 220 $cb->{native_to_perl}, 221 $cb->{perl_to_native_post}, 222 $argument_count, 223 ); 224 225 $self->{tp}->set_alias($alias, $type); 226 227 $self; 228} 229 230 231sub load_custom_type 232{ 233 my($self, $name, $alias, @type_args) = @_; 234 235 croak "usage: \$ffi->load_custom_type(\$name, \$alias, ...)" 236 unless defined $name && defined $alias; 237 238 $name = "FFI::Platypus::Type$name" if $name =~ /^::/; 239 $name = "FFI::Platypus::Type::$name" unless $name =~ /::/; 240 241 unless($name->can("ffi_custom_type_api_1")) 242 { 243 my $pm = "$name.pm"; 244 $pm =~ s/::/\//g; 245 eval { require $pm }; 246 warn $@ if $@; 247 } 248 249 unless($name->can("ffi_custom_type_api_1")) 250 { 251 croak "$name does not appear to conform to the custom type API"; 252 } 253 254 my $cb = $name->ffi_custom_type_api_1($self, @type_args); 255 $self->custom_type($alias => $cb); 256 257 $self; 258} 259 260 261sub types 262{ 263 my($self) = @_; 264 $self = $self->new unless ref $self && eval { $self->isa('FFI::Platypus') }; 265 sort $self->{tp}->list_types; 266} 267 268 269sub type_meta 270{ 271 my($self, $name) = @_; 272 $self = $self->new unless ref $self && eval { $self->isa('FFI::Platypus') }; 273 $self->{tp}->parse($name)->meta; 274} 275 276 277sub mangler 278{ 279 my($self, $sub) = @_; 280 $self->{mangler} = $self->{mymangler} = $sub; 281} 282 283 284sub function 285{ 286 my $wrapper; 287 $wrapper = pop if ref $_[-1] eq 'CODE'; 288 289 croak "usage \$ffi->function( \$name, \\\@arguments, [\\\@var_args], [\$return_type])" unless @_ >= 3 && @_ <= 6; 290 291 my $self = shift; 292 my $name = shift; 293 my $fixed_args = shift; 294 my $var_args; 295 $var_args = shift if defined $_[0] && ref($_[0]) eq 'ARRAY'; 296 my $ret = shift; 297 $ret = 'void' unless defined $ret; 298 299 # special case: treat a single void argument type as an empty list of 300 # arguments, a la olde timey C compilers. 301 if( (!defined $var_args) && @$fixed_args == 1 && $fixed_args->[0] eq 'void' ) 302 { 303 $fixed_args = []; 304 } 305 306 my $fixed_arg_count = defined $var_args ? scalar(@$fixed_args) : -1; 307 308 my @args = map { $self->{tp}->parse($_) || croak "unknown type: $_" } @$fixed_args; 309 if($var_args) 310 { 311 push @args, map { 312 my $type = $self->{tp}->parse($_); 313 # https://github.com/PerlFFI/FFI-Platypus/issues/323 314 $type->type_code == 67 ? $self->{tp}->parse('double') : $type 315 } @$var_args; 316 } 317 318 $ret = $self->{tp}->parse($ret) || croak "unknown type: $ret"; 319 my $address = $name =~ /^-?[0-9]+$/ ? $name : $self->find_symbol($name); 320 croak "unable to find $name" unless defined $address || $self->ignore_not_found; 321 return unless defined $address; 322 $address = @args > 0 ? _cast1() : _cast0() if $address == 0; 323 my $function = FFI::Platypus::Function::Function->new($self, $address, $self->{abi}, $fixed_arg_count, $ret, @args); 324 $wrapper 325 ? FFI::Platypus::Function::Wrapper->new($function, $wrapper) 326 : $function; 327} 328 329sub _function_meta 330{ 331 # NOTE: may be upgraded to a documented function one day, 332 # but shouldn't be used externally as we will rename it 333 # if that happens. 334 my($self, $name, $meta, $args, $ret) = @_; 335 $args = ['opaque','int',@$args]; 336 $self->function( 337 $name, $args, $ret, sub { 338 my $xsub = shift; 339 $xsub->($meta, scalar(@_), @_); 340 }, 341 ); 342} 343 344 345sub attach 346{ 347 my $wrapper; 348 $wrapper = pop if ref $_[-1] eq 'CODE'; 349 350 my $self = shift; 351 my $name = shift; 352 my $args = shift; 353 my $varargs; 354 $varargs = shift if defined $_[0] && ref($_[0]) eq 'ARRAY'; 355 my $ret = shift; 356 my $proto = shift; 357 358 $ret = 'void' unless defined $ret; 359 360 my($c_name, $perl_name) = ref($name) ? @$name : ($name, $name); 361 362 croak "you tried to provide a perl name that looks like an address" 363 if $perl_name =~ /^-?[0-9]+$/; 364 365 my $function = $varargs 366 ? $self->function($c_name, $args, $varargs, $ret, $wrapper) 367 : $self->function($c_name, $args, $ret, $wrapper); 368 369 if(defined $function) 370 { 371 $function->attach($perl_name, $proto); 372 } 373 374 $self; 375} 376 377 378sub closure 379{ 380 my($self, $coderef) = @_; 381 croak "not a coderef" unless ref $coderef eq 'CODE'; 382 require FFI::Platypus::Closure; 383 FFI::Platypus::Closure->new($coderef); 384} 385 386 387sub cast 388{ 389 $_[0]->function(0 => [$_[1]] => $_[2])->call($_[3]); 390} 391 392 393sub attach_cast 394{ 395 my($self, $name, $type1, $type2, $wrapper) = @_; 396 my $caller = caller; 397 $name = join '::', $caller, $name unless $name =~ /::/; 398 if(defined $wrapper && ref($wrapper) eq 'CODE') 399 { 400 $self->attach([0 => $name] => [$type1] => $type2 => '$', $wrapper); 401 } 402 else 403 { 404 $self->attach([0 => $name] => [$type1] => $type2 => '$'); 405 } 406 $self; 407} 408 409 410sub sizeof 411{ 412 my($self,$name) = @_; 413 ref $self 414 ? $self->{tp}->parse($name)->sizeof 415 : $self->new->sizeof($name); 416} 417 418 419sub alignof 420{ 421 my($self, $name) = @_; 422 ref $self 423 ? $self->{tp}->parse($name)->alignof 424 : $self->new->alignof($name); 425} 426 427 428sub kindof 429{ 430 my($self, $name) = @_; 431 ref $self 432 ? $self->{tp}->parse($name)->kindof 433 : $self->new->kindof($name); 434} 435 436 437sub countof 438{ 439 my($self, $name) = @_; 440 ref $self 441 ? $self->{tp}->parse($name)->countof 442 : $self->new->countof($name); 443} 444 445 446sub def 447{ 448 my $self = shift; 449 my $package = shift || caller; 450 my $type = shift; 451 if(@_) 452 { 453 $self->type($type); 454 $self->{def}->{$package}->{$type} = shift; 455 } 456 $self->{def}->{$package}->{$type}; 457} 458 459 460sub unitof 461{ 462 my($self, $name) = @_; 463 ref $self 464 ? $self->{tp}->parse($name)->unitof 465 : $self->new->unitof($name); 466} 467 468 469sub find_lib 470{ 471 my $self = shift; 472 require FFI::CheckLib; 473 $self->lib(FFI::CheckLib::find_lib(@_)); 474 $self; 475} 476 477 478sub find_symbol 479{ 480 my($self, $name) = @_; 481 482 $self->{mangler} ||= $self->{mymangler}; 483 484 unless(defined $self->{mangler}) 485 { 486 my $class = _lang_class($self->{lang}); 487 if($class->can('mangler')) 488 { 489 $self->{mangler} = $class->mangler($self->lib); 490 } 491 else 492 { 493 $self->{mangler} = sub { $_[0] }; 494 } 495 } 496 497 foreach my $path (@{ $self->{lib} }) 498 { 499 my $handle = do { no warnings; $self->{handles}->{$path||0} } || FFI::Platypus::DL::dlopen($path, FFI::Platypus::DL::RTLD_PLATYPUS_DEFAULT()); 500 unless($handle) 501 { 502 warn "warning: error loading $path: ", FFI::Platypus::DL::dlerror() 503 if $self->{api} > 0 || $ENV{FFI_PLATYPUS_DLERROR}; 504 next; 505 } 506 my $address = FFI::Platypus::DL::dlsym($handle, $self->{mangler}->($name)); 507 if($address) 508 { 509 $self->{handles}->{$path||0} = $handle; 510 return $address; 511 } 512 else 513 { 514 FFI::Platypus::DL::dlclose($handle) unless $self->{handles}->{$path||0}; 515 } 516 } 517 return; 518} 519 520 521sub bundle 522{ 523 croak "bundle method only available with api => 1 or better" if $_[0]->{api} < 1; 524 require FFI::Platypus::Bundle; 525 goto &_bundle; 526} 527 528 529sub package 530{ 531 croak "package method only available with api => 0" if $_[0]->{api} > 0; 532 require FFI::Platypus::Legacy; 533 goto &_package; 534} 535 536 537sub abis 538{ 539 require FFI::Platypus::ShareConfig; 540 FFI::Platypus::ShareConfig->get("abi"); 541} 542 543 544sub abi 545{ 546 my($self, $newabi) = @_; 547 unless($newabi =~ /^[0-9]+$/) 548 { 549 unless(defined $self->abis->{$newabi}) 550 { 551 croak "no such ABI: $newabi"; 552 } 553 $newabi = $self->abis->{$newabi}; 554 } 555 556 unless(FFI::Platypus::ABI::verify($newabi)) 557 { 558 croak "no such ABI: $newabi"; 559 } 560 561 $self->{abi} = $newabi; 562 $self->{tp}->abi($newabi); 563 564 $self; 565} 566 567sub DESTROY 568{ 569 my($self) = @_; 570 foreach my $fini (@{ $self->{fini} }) 571 { 572 $fini->($self); 573 } 574 foreach my $handle (values %{ $self->{handles} }) 575 { 576 next unless $handle; 577 FFI::Platypus::DL::dlclose($handle); 578 } 579 delete $self->{handles}; 580} 581 5821; 583 584__END__ 585 586=pod 587 588=encoding UTF-8 589 590=head1 NAME 591 592FFI::Platypus - Write Perl bindings to non-Perl libraries with FFI. No XS required. 593 594=head1 VERSION 595 596version 1.56 597 598=head1 SYNOPSIS 599 600 use FFI::Platypus 1.00; 601 602 # for all new code you should use api => 1 603 my $ffi = FFI::Platypus->new( api => 1 ); 604 $ffi->lib(undef); # search libc 605 606 # call dynamically 607 $ffi->function( puts => ['string'] => 'int' )->call("hello world"); 608 609 # attach as a xsub and call (much faster) 610 $ffi->attach( puts => ['string'] => 'int' ); 611 puts("hello world"); 612 613=head1 DESCRIPTION 614 615Platypus is a library for creating interfaces to machine code libraries 616written in languages like C, L<C++|FFI::Platypus::Lang::CPP>, 617L<Go|FFI::Platypus::Lang::Go>, 618L<Fortran|FFI::Platypus::Lang::Fortran>, 619L<Rust|FFI::Platypus::Lang::Rust>, 620L<Pascal|FFI::Platypus::Lang::Pascal>. Essentially anything that gets 621compiled into machine code. This implementation uses C<libffi> to 622accomplish this task. C<libffi> is battle tested by a number of other 623scripting and virtual machine languages, such as Python and Ruby to 624serve a similar role. There are a number of reasons why you might want 625to write an extension with Platypus instead of XS: 626 627=over 4 628 629=item FFI / Platypus does not require messing with the guts of Perl 630 631XS is less of an API and more of the guts of perl splayed out to do 632whatever you want. That may at times be very powerful, but it can also 633be a frustrating exercise in hair pulling. 634 635=item FFI / Platypus is portable 636 637Lots of languages have FFI interfaces, and it is subjectively easier to 638port an extension written in FFI in Perl or another language to FFI in 639another language or Perl. One goal of the Platypus Project is to reduce 640common interface specifications to a common format like JSON that could 641be shared between different languages. 642 643=item FFI / Platypus could be a bridge to Raku 644 645One of those "other" languages could be Raku and Raku already has an 646FFI interface I am told. 647 648=item FFI / Platypus can be reimplemented 649 650In a bright future with multiple implementations of Perl 5, each 651interpreter will have its own implementation of Platypus, allowing 652extensions to be written once and used on multiple platforms, in much 653the same way that Ruby-FFI extensions can be use in Ruby, JRuby and 654Rubinius. 655 656=item FFI / Platypus is pure perl (sorta) 657 658One Platypus script or module works on any platform where the libraries 659it uses are available. That means you can deploy your Platypus script 660in a shared filesystem where they may be run on different platforms. It 661also means that Platypus modules do not need to be installed in the 662platform specific Perl library path. 663 664=item FFI / Platypus is not C or C++ centric 665 666XS is implemented primarily as a bunch of C macros, which requires at 667least some understanding of C, the C pre-processor, and some C++ caveats 668(since on some platforms Perl is compiled and linked with a C++ 669compiler). Platypus on the other hand could be used to call other 670compiled languages, like L<Fortran|FFI::Platypus::Lang::Fortran>, 671L<Go|FFI::Platypus::Lang::Go>, 672L<Rust|FFI::Platypus::Lang::Rust>, 673L<Pascal|FFI::Platypus::Lang::Pascal>, L<C++|FFI::Platypus::Lang::CPP>, 674or even L<assembly|FFI::Platypus::Lang::ASM>, allowing you to focus 675on your strengths. 676 677=item FFI / Platypus does not require a parser 678 679L<Inline> isolates the extension developer from XS to some extent, but 680it also requires a parser. The various L<Inline> language bindings are 681a great technical achievement, but I think writing a parser for every 682language that you want to interface with is a bit of an anti-pattern. 683 684=back 685 686This document consists of an API reference, a set of examples, some 687support and development (for contributors) information. If you are new 688to Platypus or FFI, you may want to skip down to the 689L<EXAMPLES|/EXAMPLES> to get a taste of what you can do with Platypus. 690 691Platypus has extensive documentation of types at L<FFI::Platypus::Type> 692and its custom types API at L<FFI::Platypus::API>. 693 694You are B<strongly> encouraged to use API level 1 for all new code. 695There are a number of improvements and design fixes that you get 696for free. You should even consider updating existing modules to 697use API level 1 where feasible. How do I do that you might ask? 698Simply pass in the API level to the platypus constructor. 699 700 my $ffi = FFI::Platypus->new( api => 1 ); 701 702The Platypus documentation has already been updated to assume API 703level 1. 704 705=for stopwords ØMQ 706 707=head1 CONSTRUCTORS 708 709=head2 new 710 711 my $ffi = FFI::Platypus->new( api => 1, %options); 712 713Create a new instance of L<FFI::Platypus>. 714 715Any types defined with this instance will be valid for this instance 716only, so you do not need to worry about stepping on the toes of other 717CPAN FFI / Platypus Authors. 718 719Any functions found will be out of the list of libraries specified with 720the L<lib|/lib> attribute. 721 722=head3 options 723 724=over 4 725 726=item api 727 728[version 0.91] 729 730Sets the API level. Legal values are 731 732=over 733 734=item C<0> 735 736Original API level. See L<FFI::Platypus::TypeParser::Version0> for details 737on the differences. 738 739=item C<1> 740 741Enable the next generation type parser which allows pass-by-value records 742and type decoration on basic types. Using API level 1 prior to Platypus 743version 1.00 will trigger a (noisy) warning. 744 745All new code should be written with this set to 1! The Platypus documentation 746assumes this api level is set. 747 748=item C<2> 749 750Enable version 2 API, which is currently experimental. Using API level 2 prior 751to Platypus version 2.00 will trigger a (noisy) warning. 752 753API version 2 is identical to version 1, except: 754 755=over 4 756 757=item Pointer functions that return C<NULL> will return C<undef> instead of empty list 758 759This fixes a long standing design bug in Platypus. 760 761=item Array references may be passed to pointer argument types 762 763This replicates the behavior of array argument types with no size. So the types C<sint8*> and C<sint8[]> 764behave identically when an array reference is passed in. They differ in that, as before, you can 765pass a scalar reference into type C<sint8*>. 766 767=back 768 769=back 770 771=item lib 772 773Either a pathname (string) or a list of pathnames (array ref of strings) 774to pre-populate the L<lib|/lib> attribute. Use C<[undef]> to search the 775current process for symbols. 776 7770.48 778 779C<undef> (without the array reference) can be used to search the current 780process for symbols. 781 782=item ignore_not_found 783 784[version 0.15] 785 786Set the L<ignore_not_found|/ignore_not_found> attribute. 787 788=item lang 789 790[version 0.18] 791 792Set the L<lang|/lang> attribute. 793 794=back 795 796=head1 ATTRIBUTES 797 798=head2 lib 799 800 $ffi->lib($path1, $path2, ...); 801 my @paths = $ffi->lib; 802 803The list of libraries to search for symbols in. 804 805The most portable and reliable way to find dynamic libraries is by using 806L<FFI::CheckLib>, like this: 807 808 use FFI::CheckLib 0.06; 809 $ffi->lib(find_lib_or_die lib => 'archive'); 810 # finds libarchive.so on Linux 811 # libarchive.bundle on OS X 812 # libarchive.dll (or archive.dll) on Windows 813 # cygarchive-13.dll on Cygwin 814 # ... 815 # and will die if it isn't found 816 817L<FFI::CheckLib> has a number of options, such as checking for specific 818symbols, etc. You should consult the documentation for that module. 819 820As a special case, if you add C<undef> as a "library" to be searched, 821Platypus will also search the current process for symbols. This is 822mostly useful for finding functions in the standard C library, without 823having to know the name of the standard c library for your platform (as 824it turns out it is different just about everywhere!). 825 826You may also use the L</find_lib> method as a shortcut: 827 828 $ffi->find_lib( lib => 'archive' ); 829 830=head2 ignore_not_found 831 832[version 0.15] 833 834 $ffi->ignore_not_found(1); 835 my $ignore_not_found = $ffi->ignore_not_found; 836 837Normally the L<attach|/attach> and L<function|/function> methods will 838throw an exception if it cannot find the name of the function you 839provide it. This will change the behavior such that 840L<function|/function> will return C<undef> when the function is not 841found and L<attach|/attach> will ignore functions that are not found. 842This is useful when you are writing bindings to a library and have many 843optional functions and you do not wish to wrap every call to 844L<function|/function> or L<attach|/attach> in an C<eval>. 845 846=head2 lang 847 848[version 0.18] 849 850 $ffi->lang($language); 851 852Specifies the foreign language that you will be interfacing with. The 853default is C. The foreign language specified with this attribute 854changes the default native types (for example, if you specify 855L<Rust|FFI::Platypus::Lang::Rust>, you will get C<i32> as an alias for 856C<sint32> instead of C<int> as you do with L<C|FFI::Platypus::Lang::C>). 857 858If the foreign language plugin supports it, this will also enable 859Platypus to find symbols using the demangled names (for example, if you 860specify L<CPP|FFI::Platypus::Lang::CPP> for C++ you can use method names 861like C<Foo::get_bar()> with L</attach> or L</function>. 862 863=head2 api 864 865[version 1.11] 866 867 my $level = $ffi->api; 868 869Returns the API level of the Platypus instance. 870 871=head1 METHODS 872 873=head2 type 874 875 $ffi->type($typename); 876 $ffi->type($typename => $alias); 877 878Define a type. The first argument is the native or C name of the type. 879The second argument (optional) is an alias name that you can use to 880refer to this new type. See L<FFI::Platypus::Type> for legal type 881definitions. 882 883Examples: 884 885 $ffi->type('sint32'); # only checks to see that sint32 is a valid type 886 $ffi->type('sint32' => 'myint'); # creates an alias myint for sint32 887 $ffi->type('bogus'); # dies with appropriate diagnostic 888 889=head2 custom_type 890 891 $ffi->custom_type($alias => { 892 native_type => $native_type, 893 native_to_perl => $coderef, 894 perl_to_native => $coderef, 895 perl_to_native_post => $coderef, 896 }); 897 898Define a custom type. See L<FFI::Platypus::Type#Custom-Types> for details. 899 900=head2 load_custom_type 901 902 $ffi->load_custom_type($name => $alias, @type_args); 903 904Load the custom type defined in the module I<$name>, and make an alias 905I<$alias>. If the custom type requires any arguments, they may be passed 906in as I<@type_args>. See L<FFI::Platypus::Type#Custom-Types> for 907details. 908 909If I<$name> contains C<::> then it will be assumed to be a fully 910qualified package name. If not, then C<FFI::Platypus::Type::> will be 911prepended to it. 912 913=head2 types 914 915 my @types = $ffi->types; 916 my @types = FFI::Platypus->types; 917 918Returns the list of types that FFI knows about. This will include the 919native C<libffi> types (example: C<sint32>, C<opaque> and C<double>) and 920the normal C types (example: C<unsigned int>, C<uint32_t>), any types 921that you have defined using the L<type|/type> method, and custom types. 922 923The list of types that Platypus knows about varies somewhat from 924platform to platform, L<FFI::Platypus::Type> includes a list of the core 925types that you can always count on having access to. 926 927It can also be called as a class method, in which case, no user defined 928or custom types will be included in the list. 929 930=head2 type_meta 931 932 my $meta = $ffi->type_meta($type_name); 933 my $meta = FFI::Platypus->type_meta($type_name); 934 935Returns a hash reference with the meta information for the given type. 936 937It can also be called as a class method, in which case, you won't be 938able to get meta data on user defined types. 939 940The format of the meta data is implementation dependent and subject to 941change. It may be useful for display or debugging. 942 943Examples: 944 945 my $meta = $ffi->type_meta('int'); # standard int type 946 my $meta = $ffi->type_meta('int[64]'); # array of 64 ints 947 $ffi->type('int[128]' => 'myintarray'); 948 my $meta = $ffi->type_meta('myintarray'); # array of 128 ints 949 950=head2 mangler 951 952 $ffi->mangler(\&mangler); 953 954Specify a customer mangler to be used for symbol lookup. This is usually useful 955when you are writing bindings for a library where all of the functions have the 956same prefix. Example: 957 958 $ffi->mangler(sub { 959 my($symbol) = @_; 960 return "foo_$symbol"; 961 }); 962 963 $ffi->function( get_bar => [] => 'int' ); # attaches foo_get_bar 964 965 my $f = $ffi->function( set_baz => ['int'] => 'void' ); 966 $f->call(22); # calls foo_set_baz 967 968=head2 function 969 970 my $function = $ffi->function($name => \@argument_types => $return_type); 971 my $function = $ffi->function($address => \@argument_types => $return_type); 972 my $function = $ffi->function($name => \@argument_types => $return_type, \&wrapper); 973 my $function = $ffi->function($address => \@argument_types => $return_type, \&wrapper); 974 975Returns an object that is similar to a code reference in that it can be 976called like one. 977 978Caveat: many situations require a real code reference, so at the price 979of a performance penalty you can get one like this: 980 981 my $function = $ffi->function(...); 982 my $coderef = sub { $function->(@_) }; 983 984It may be better, and faster to create a real Perl function using the 985L<attach|/attach> method. 986 987In addition to looking up a function by name you can provide the address 988of the symbol yourself: 989 990 my $address = $ffi->find_symbol('my_function'); 991 my $function = $ffi->function($address => ...); 992 993Under the covers, L<function|/function> uses L<find_symbol|/find_symbol> 994when you provide it with a name, but it is useful to keep this in mind 995as there are alternative ways of obtaining a functions address. 996Example: a C function could return the address of another C function 997that you might want to call, or modules such as L<FFI::TinyCC> produce 998machine code at runtime that you can call from Platypus. 999 1000[version 0.76] 1001 1002If the last argument is a code reference, then it will be used as a 1003wrapper around the function when called. The first argument to the wrapper 1004will be the inner function, or if it is later attached an xsub. This can be 1005used if you need to verify/modify input/output data. 1006 1007Examples: 1008 1009 my $function = $ffi->function('my_function_name', ['int', 'string'] => 'string'); 1010 my $return_string = $function->(1, "hi there"); 1011 1012[version 0.91] 1013 1014 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type); 1015 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type, \&wrapper); 1016 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types); 1017 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => \&wrapper); 1018 1019Version 0.91 and later allows you to creat functions for c variadic functions 1020(such as printf, scanf, etc) which can take a variable number of arguments. 1021The first set of arguments are the fixed set, the second set are the variable 1022arguments to bind with. The variable argument types must be specified in order 1023to create a function object, so if you need to call variadic function with 1024different set of arguments then you will need to create a new function object 1025each time: 1026 1027 # int printf(const char *fmt, ...); 1028 $ffi->function( printf => ['string'] => ['int'] => 'int' ) 1029 ->call("print integer %d\n", 42); 1030 $ffi->function( printf => ['string'] => ['string'] => 'int' ) 1031 ->call("print string %s\n", 'platypus'); 1032 1033Some older versions of libffi and possibly some platforms may not support 1034variadic functions. If you try to create a one, then an exception will be 1035thrown. 1036 1037[version 1.26] 1038 1039If the return type is omitted then C<void> will be the assumed return type. 1040 1041=head2 attach 1042 1043 $ffi->attach($name => \@argument_types => $return_type); 1044 $ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type); 1045 $ffi->attach([$address => $perl_name] => \@argument_types => $return_type); 1046 $ffi->attach($name => \@argument_types => $return_type, \&wrapper); 1047 $ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type, \&wrapper); 1048 $ffi->attach([$address => $perl_name] => \@argument_types => $return_type, \&wrapper); 1049 1050Find and attach a C function as a real live Perl xsub. The advantage of 1051attaching a function over using the L<function|/function> method is that 1052it is much much much faster since no object resolution needs to be done. 1053The disadvantage is that it locks the function and the L<FFI::Platypus> 1054instance into memory permanently, since there is no way to deallocate an 1055xsub. 1056 1057If just one I<$name> is given, then the function will be attached in 1058Perl with the same name as it has in C. The second form allows you to 1059give the Perl function a different name. You can also provide an 1060address (the third form), just like with the L<function|/function> 1061method. 1062 1063Examples: 1064 1065 $ffi->attach('my_function_name', ['int', 'string'] => 'string'); 1066 $ffi->attach(['my_c_function_name' => 'my_perl_function_name'], ['int', 'string'] => 'string'); 1067 my $string1 = my_function_name($int); 1068 my $string2 = my_perl_function_name($int); 1069 1070[version 0.20] 1071 1072If the last argument is a code reference, then it will be used as a 1073wrapper around the attached xsub. The first argument to the wrapper 1074will be the inner xsub. This can be used if you need to verify/modify 1075input/output data. 1076 1077Examples: 1078 1079 $ffi->attach('my_function', ['int', 'string'] => 'string', sub { 1080 my($my_function_xsub, $integer, $string) = @_; 1081 $integer++; 1082 $string .= " and another thing"; 1083 my $return_string = $my_function_xsub->($integer, $string); 1084 $return_string =~ s/Belgium//; # HHGG remove profanity 1085 $return_string; 1086 }); 1087 1088[version 0.91] 1089 1090 $ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type); 1091 $ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type, \&wrapper); 1092 1093As of version 0.91 you can attach a variadic functions, if it is supported 1094by the platform / libffi that you are using. For details see the C<function> 1095documentation. If not supported by the implementation then an exception 1096will be thrown. 1097 1098=head2 closure 1099 1100 my $closure = $ffi->closure($coderef); 1101 my $closure = FFI::Platypus->closure($coderef); 1102 1103Prepares a code reference so that it can be used as a FFI closure (a 1104Perl subroutine that can be called from C code). For details on 1105closures, see L<FFI::Platypus::Type#Closures> and L<FFI::Platypus::Closure>. 1106 1107=head2 cast 1108 1109 my $converted_value = $ffi->cast($original_type, $converted_type, $original_value); 1110 1111The C<cast> function converts an existing I<$original_value> of type 1112I<$original_type> into one of type I<$converted_type>. Not all types 1113are supported, so care must be taken. For example, to get the address 1114of a string, you can do this: 1115 1116 my $address = $ffi->cast('string' => 'opaque', $string_value); 1117 1118Something that won't work is trying to cast an array to anything: 1119 1120 my $address = $ffi->cast('int[10]' => 'opaque', \@list); # WRONG 1121 1122=head2 attach_cast 1123 1124 $ffi->attach_cast("cast_name", $original_type, $converted_type); 1125 $ffi->attach_cast("cast_name", $original_type, $converted_type, \&wrapper); 1126 my $converted_value = cast_name($original_value); 1127 1128This function attaches a cast as a permanent xsub. This will make it 1129faster and may be useful if you are calling a particular cast a lot. 1130 1131[version 1.26] 1132 1133A wrapper may be added as the last argument to C<attach_cast> and works 1134just like the wrapper for C<attach> and C<function> methods. 1135 1136=head2 sizeof 1137 1138 my $size = $ffi->sizeof($type); 1139 my $size = FFI::Platypus->sizeof($type); 1140 1141Returns the total size of the given type in bytes. For example to get 1142the size of an integer: 1143 1144 my $intsize = $ffi->sizeof('int'); # usually 4 1145 my $longsize = $ffi->sizeof('long'); # usually 4 or 8 depending on platform 1146 1147You can also get the size of arrays 1148 1149 my $intarraysize = $ffi->sizeof('int[64]'); # usually 4*64 1150 my $intarraysize = $ffi->sizeof('long[64]'); # usually 4*64 or 8*64 1151 # depending on platform 1152 1153Keep in mind that "pointer" types will always be the pointer / word size 1154for the platform that you are using. This includes strings, opaque and 1155pointers to other types. 1156 1157This function is not very fast, so you might want to save this value as 1158a constant, particularly if you need the size in a loop with many 1159iterations. 1160 1161=head2 alignof 1162 1163[version 0.21] 1164 1165 my $align = $ffi->alignof($type); 1166 1167Returns the alignment of the given type in bytes. 1168 1169=head2 kindof 1170 1171[version 1.24] 1172 1173 my $kind = $ffi->kindof($type); 1174 1175Returns the kind of a type. This is a string with a value of one of 1176 1177=over 4 1178 1179=item C<void> 1180 1181=item C<scalar> 1182 1183=item C<string> 1184 1185=item C<closure> 1186 1187=item C<record> 1188 1189=item C<record-value> 1190 1191=item C<pointer> 1192 1193=item C<array> 1194 1195=item C<object> 1196 1197=back 1198 1199=head2 countof 1200 1201[version 1.24] 1202 1203 my $count = $ffi->countof($type); 1204 1205For array types returns the number of elements in the array (returns 0 for variable length array). 1206For the C<void> type returns 0. Returns 1 for all other types. 1207 1208=head2 def 1209 1210[version 1.24] 1211 1212 $ffi->def($package, $type, $value); 1213 my $value = $ff->def($package, $type); 1214 1215This method allows you to store data for types. If the C<$package> is not provided, then the 1216caller's package will be used. C<$type> must be a legal Platypus type for the L<FFI::Platypus> 1217instance. 1218 1219=head2 unitof 1220 1221[version 1.24] 1222 1223 my $unittype = $ffi->unitof($type); 1224 1225For array and pointer types, returns the basic type without the array or pointer part. 1226In other words, for C<sin16[]> or C<sint16*> it will return C<sint16>. 1227 1228=head2 find_lib 1229 1230[version 0.20] 1231 1232 $ffi->find_lib( lib => $libname ); 1233 1234This is just a shortcut for calling L<FFI::CheckLib#find_lib> and 1235updating the L</lib> attribute appropriately. Care should be taken 1236though, as this method simply passes its arguments to 1237L<FFI::CheckLib#find_lib>, so if your module or script is depending on a 1238specific feature in L<FFI::CheckLib> then make sure that you update your 1239prerequisites appropriately. 1240 1241=head2 find_symbol 1242 1243 my $address = $ffi->find_symbol($name); 1244 1245Return the address of the given symbol (usually function). 1246 1247=head2 bundle 1248 1249[version 0.96 api = 1+] 1250 1251 $ffi->bundle($package, \@args); 1252 $ffi->bundle(\@args); 1253 $ffi->bundle($package); 1254 $ffi->bundle; 1255 1256This is an interface for bundling compiled code with your 1257distribution intended to eventually replace the C<package> method documented 1258above. See L<FFI::Platypus::Bundle> for details on how this works. 1259 1260=head2 package 1261 1262[version 0.15 api = 0] 1263 1264 $ffi->package($package, $file); # usually __PACKAGE__ and __FILE__ can be used 1265 $ffi->package; # autodetect 1266 1267B<Note>: This method is officially discouraged in favor of C<bundle> 1268described above. 1269 1270If you use L<FFI::Build> (or the older deprecated L<Module::Build::FFI> 1271to bundle C code with your distribution, you can use this method to tell 1272the L<FFI::Platypus> instance to look for symbols that came with the 1273dynamic library that was built when your distribution was installed. 1274 1275=head2 abis 1276 1277 my $href = $ffi->abis; 1278 my $href = FFI::Platypus->abis; 1279 1280Get the legal ABIs supported by your platform and underlying 1281implementation. What is supported can vary a lot by CPU and by 1282platform, or even between 32 and 64 bit on the same CPU and platform. 1283They keys are the "ABI" names, also known as "calling conventions". The 1284values are integers used internally by the implementation to represent 1285those ABIs. 1286 1287=head2 abi 1288 1289 $ffi->abi($name); 1290 1291Set the ABI or calling convention for use in subsequent calls to 1292L</function> or L</attach>. May be either a string name or integer 1293value from the L</abis> method above. 1294 1295=head1 EXAMPLES 1296 1297Here are some examples. These examples 1298are provided in full with the Platypus distribution in the "examples" 1299directory. There are also some more examples in L<FFI::Platypus::Type> 1300that are related to types. 1301 1302=head2 Integer conversions 1303 1304 use FFI::Platypus 1.00; 1305 1306 my $ffi = FFI::Platypus->new( api => 1 ); 1307 $ffi->lib(undef); 1308 1309 $ffi->attach(puts => ['string'] => 'int'); 1310 $ffi->attach(atoi => ['string'] => 'int'); 1311 1312 puts(atoi('56')); 1313 1314B<Discussion>: C<puts> and C<atoi> should be part of the standard C 1315library on all platforms. C<puts> prints a string to standard output, 1316and C<atoi> converts a string to integer. Specifying C<undef> as a 1317library tells Platypus to search the current process for symbols, which 1318includes the standard c library. 1319 1320=head2 libnotify 1321 1322 use FFI::CheckLib; 1323 use FFI::Platypus 1.00; 1324 1325 # NOTE: I ported this from anoter Perl FFI library and it seems to work most 1326 # of the time, but also seems to SIGSEGV sometimes. I saw the same behavior 1327 # in the old version, and am not really familiar with the libnotify API to 1328 # say what is the cause. Patches welcome to fix it. 1329 1330 my $ffi = FFI::Platypus->new( api => 1 ); 1331 $ffi->lib(find_lib_or_exit lib => 'notify'); 1332 1333 $ffi->attach(notify_init => ['string'] => 'void'); 1334 $ffi->attach(notify_uninit => [] => 'void'); 1335 $ffi->attach([notify_notification_new => 'notify_new'] => ['string', 'string', 'string'] => 'opaque'); 1336 $ffi->attach([notify_notification_update => 'notify_update'] => ['opaque', 'string', 'string', 'string'] => 'void'); 1337 $ffi->attach([notify_notification_show => 'notify_show'] => ['opaque', 'opaque'] => 'void'); 1338 1339 notify_init('FFI::Platypus'); 1340 my $n = notify_new('','',''); 1341 notify_update($n, 'FFI::Platypus', 'It works!!!', 'media-playback-start'); 1342 notify_show($n, undef); 1343 notify_uninit(); 1344 1345B<Discussion>: libnotify is a desktop GUI notification library for the 1346GNOME Desktop environment. This script sends a notification event that 1347should show up as a balloon, for me it did so in the upper right hand 1348corner of my screen. 1349 1350The most portable way to find the correct name and location of a dynamic 1351library is via the L<FFI::CheckLib#find_lib> family of functions. If 1352you are putting together a CPAN distribution, you should also consider 1353using L<FFI::CheckLib#check_lib_or_exit> function in your C<Build.PL> or 1354C<Makefile.PL> file (If you are using L<Dist::Zilla>, check out the 1355L<Dist::Zilla::Plugin::FFI::CheckLib> plugin). This will provide a user 1356friendly diagnostic letting the user know that the required library is 1357missing, and reduce the number of bogus CPAN testers results that you 1358will get. 1359 1360Also in this example, we rename some of the functions when they are 1361placed into Perl space to save typing: 1362 1363 $ffi->attach( [notify_notification_new => 'notify_new'] 1364 => ['string','string','string'] 1365 => 'opaque' 1366 ); 1367 1368When you specify a list reference as the "name" of the function the 1369first element is the symbol name as understood by the dynamic library. 1370The second element is the name as it will be placed in Perl space. 1371 1372Later, when we call C<notify_new>: 1373 1374 my $n = notify_new('','',''); 1375 1376We are really calling the C function C<notify_notification_new>. 1377 1378=head2 Allocating and freeing memory 1379 1380 use FFI::Platypus 1.00; 1381 use FFI::Platypus::Memory qw( malloc free memcpy ); 1382 1383 my $ffi = FFI::Platypus->new( api => 1 ); 1384 my $buffer = malloc 12; 1385 1386 memcpy $buffer, $ffi->cast('string' => 'opaque', "hello there"), length "hello there\0"; 1387 1388 print $ffi->cast('opaque' => 'string', $buffer), "\n"; 1389 1390 free $buffer; 1391 1392B<Discussion>: C<malloc> and C<free> are standard memory allocation 1393functions available from the standard c library and. Interfaces to 1394these and other memory related functions are provided by the 1395L<FFI::Platypus::Memory> module. 1396 1397=head2 structured data records 1398 1399 use FFI::Platypus 1.00; 1400 use FFI::C; 1401 1402 my $ffi = FFI::Platypus->new( 1403 api => 1, 1404 lib => [undef], 1405 ); 1406 FFI::C->ffi($ffi); 1407 1408 package Unix::TimeStruct { 1409 1410 FFI::C->struct(tm => [ 1411 tm_sec => 'int', 1412 tm_min => 'int', 1413 tm_hour => 'int', 1414 tm_mday => 'int', 1415 tm_mon => 'int', 1416 tm_year => 'int', 1417 tm_wday => 'int', 1418 tm_yday => 'int', 1419 tm_isdst => 'int', 1420 tm_gmtoff => 'long', 1421 _tm_zone => 'opaque', 1422 ]); 1423 1424 # For now 'string' is unsupported by FFI::C, but we 1425 # can cast the time zone from an opaque pointer to 1426 # string. 1427 sub tm_zone { 1428 my $self = shift; 1429 $ffi->cast('opaque', 'string', $self->_tm_zone); 1430 } 1431 1432 # attach the C localtime function 1433 $ffi->attach( localtime => ['time_t*'] => 'tm', sub { 1434 my($inner, $class, $time) = @_; 1435 $time = time unless defined $time; 1436 $inner->(\$time); 1437 }); 1438 } 1439 1440 # now we can actually use our Unix::TimeStruct class 1441 my $time = Unix::TimeStruct->localtime; 1442 printf "time is %d:%d:%d %s\n", 1443 $time->tm_hour, 1444 $time->tm_min, 1445 $time->tm_sec, 1446 $time->tm_zone; 1447 1448B<Discussion>: C and other machine code languages frequently provide 1449interfaces that include structured data records (known as "structs" in 1450C). They sometimes provide an API in which you are expected to 1451manipulate these records before and/or after passing them along to C 1452functions. For C pointers to structs, unions and arrays of structs and 1453unions, the easiest interface to use is via L<FFI::C>. If you are 1454working with structs that must be passed as values (not pointers), 1455then you want to use the L<FFI::Platypus::Record> class instead. 1456We will discuss this class later. 1457 1458The C C<localtime> function takes a pointer to a C struct. We simply define 1459the members of the struct using the L<FFI::C> C<struct> method. Because 1460we used the C<ffi> method to tell L<FFI::C> to use our local instance of 1461L<FFI::Platypus> it registers the C<tm> type for us, and we can just start 1462using it as a return type! 1463 1464=head2 structured data records by-value 1465 1466=head2 libuuid 1467 1468 use FFI::CheckLib; 1469 use FFI::Platypus 1.00; 1470 use FFI::Platypus::Memory qw( malloc free ); 1471 1472 my $ffi = FFI::Platypus->new( api => 1 ); 1473 $ffi->lib(find_lib_or_exit lib => 'uuid'); 1474 $ffi->type('string(37)*' => 'uuid_string'); 1475 $ffi->type('record(16)*' => 'uuid_t'); 1476 1477 $ffi->attach(uuid_generate => ['uuid_t'] => 'void'); 1478 $ffi->attach(uuid_unparse => ['uuid_t','uuid_string'] => 'void'); 1479 1480 my $uuid = "\0" x $ffi->sizeof('uuid_t'); 1481 uuid_generate($uuid); 1482 1483 my $string = "\0" x $ffi->sizeof('uuid_string'); 1484 uuid_unparse($uuid, $string); 1485 1486 print "$string\n"; 1487 1488B<Discussion>: libuuid is a library used to generate unique identifiers 1489(UUID) for objects that may be accessible beyond the local system. The 1490library is or was part of the Linux e2fsprogs package. 1491 1492Knowing the size of objects is sometimes important. In this example, we 1493use the L<sizeof|/sizeof> function to get the size of 16 characters (in 1494this case it is simply 16 bytes). We also know that the strings 1495"deparsed" by C<uuid_unparse> are exactly 37 bytes. 1496 1497=head2 puts and getpid 1498 1499 use FFI::Platypus 1.00; 1500 1501 my $ffi = FFI::Platypus->new( api => 1 ); 1502 $ffi->lib(undef); 1503 1504 $ffi->attach(puts => ['string'] => 'int'); 1505 $ffi->attach(getpid => [] => 'int'); 1506 1507 puts(getpid()); 1508 1509B<Discussion>: C<puts> is part of standard C library on all platforms. 1510C<getpid> is available on Unix type platforms. 1511 1512=head2 Math library 1513 1514 use FFI::Platypus 1.00; 1515 use FFI::CheckLib; 1516 1517 my $ffi = FFI::Platypus->new( api => 1 ); 1518 $ffi->lib(undef); 1519 $ffi->attach(puts => ['string'] => 'int'); 1520 $ffi->attach(fdim => ['double','double'] => 'double'); 1521 1522 puts(fdim(7.0, 2.0)); 1523 1524 $ffi->attach(cos => ['double'] => 'double'); 1525 1526 puts(cos(2.0)); 1527 1528 $ffi->attach(fmax => ['double', 'double'] => 'double'); 1529 1530 puts(fmax(2.0,3.0)); 1531 1532B<Discussion>: On UNIX the standard c library math functions are 1533frequently provided in a separate library C<libm>, so you could search 1534for those symbols in "libm.so", but that won't work on non-UNIX 1535platforms like Microsoft Windows. Fortunately Perl uses the math 1536library so these symbols are already in the current process so you can 1537use C<undef> as the library to find them. 1538 1539=head2 Strings 1540 1541 use FFI::Platypus 1.00; 1542 1543 my $ffi = FFI::Platypus->new( api => 1 ); 1544 $ffi->lib(undef); 1545 $ffi->attach(puts => ['string'] => 'int'); 1546 $ffi->attach(strlen => ['string'] => 'int'); 1547 1548 puts(strlen('somestring')); 1549 1550 $ffi->attach(strstr => ['string','string'] => 'string'); 1551 1552 puts(strstr('somestring', 'string')); 1553 1554 #attach puts => [string] => int; 1555 1556 puts(puts("lol")); 1557 1558 $ffi->attach(strerror => ['int'] => 'string'); 1559 1560 puts(strerror(2)); 1561 1562B<Discussion>: ASCII and UTF-8 Strings are not a native type to C<libffi> 1563but the are handled seamlessly by Platypus. If you need to talk to an 1564API that uses so called "wide" strings (APIs which use C<const wchar_t*> 1565or C<wchar_t*>), then you will want to use the wide string type plugin 1566L<FFI::Platypus::Type::WideString>. APIs which use other arbitrary 1567encodings can be accessed by converting your Perl strings manually with 1568the L<Encode> module. 1569 1570=head2 Attach function from pointer 1571 1572 use FFI::TinyCC; 1573 use FFI::Platypus 1.00; 1574 1575 my $ffi = FFI::Platypus->new( api => 1 ); 1576 my $tcc = FFI::TinyCC->new; 1577 1578 $tcc->compile_string(q{ 1579 int 1580 add(int a, int b) 1581 { 1582 return a+b; 1583 } 1584 }); 1585 1586 my $address = $tcc->get_symbol('add'); 1587 1588 $ffi->attach( [ $address => 'add' ] => ['int','int'] => 'int' ); 1589 1590 print add(1,2), "\n"; 1591 1592B<Discussion>: Sometimes you will have a pointer to a function from a 1593source other than Platypus that you want to call. You can use that 1594address instead of a function name for either of the 1595L<function|/function> or L<attach|/attach> methods. In this example we 1596use L<FFI::TinyCC> to compile a short piece of C code and to give us the 1597address of one of its functions, which we then use to create a perl xsub 1598to call it. 1599 1600L<FFI::TinyCC> embeds the Tiny C Compiler (tcc) to provide a 1601just-in-time (JIT) compilation service for FFI. 1602 1603=head2 libzmq 1604 1605 use constant ZMQ_IO_THREADS => 1; 1606 use constant ZMQ_MAX_SOCKETS => 2; 1607 use constant ZMQ_REQ => 3; 1608 use constant ZMQ_REP => 4; 1609 use FFI::CheckLib qw( find_lib_or_exit ); 1610 use FFI::Platypus 1.00; 1611 use FFI::Platypus::Memory qw( malloc ); 1612 use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar ); 1613 1614 my $endpoint = "ipc://zmq-ffi-$$"; 1615 my $ffi = FFI::Platypus->new( api => 1 ); 1616 1617 $ffi->lib(undef); # for puts 1618 $ffi->attach(puts => ['string'] => 'int'); 1619 1620 $ffi->lib(find_lib_or_exit lib => 'zmq'); 1621 $ffi->attach(zmq_version => ['int*', 'int*', 'int*'] => 'void'); 1622 1623 my($major,$minor,$patch); 1624 zmq_version(\$major, \$minor, \$patch); 1625 puts("libzmq version $major.$minor.$patch"); 1626 die "this script only works with libzmq 3 or better" unless $major >= 3; 1627 1628 $ffi->type('opaque' => 'zmq_context'); 1629 $ffi->type('opaque' => 'zmq_socket'); 1630 $ffi->type('opaque' => 'zmq_msg_t'); 1631 $ffi->attach(zmq_ctx_new => [] => 'zmq_context'); 1632 $ffi->attach(zmq_ctx_set => ['zmq_context', 'int', 'int'] => 'int'); 1633 $ffi->attach(zmq_socket => ['zmq_context', 'int'] => 'zmq_socket'); 1634 $ffi->attach(zmq_connect => ['opaque', 'string'] => 'int'); 1635 $ffi->attach(zmq_bind => ['zmq_socket', 'string'] => 'int'); 1636 $ffi->attach(zmq_send => ['zmq_socket', 'opaque', 'size_t', 'int'] => 'int'); 1637 $ffi->attach(zmq_msg_init => ['zmq_msg_t'] => 'int'); 1638 $ffi->attach(zmq_msg_recv => ['zmq_msg_t', 'zmq_socket', 'int'] => 'int'); 1639 $ffi->attach(zmq_msg_data => ['zmq_msg_t'] => 'opaque'); 1640 $ffi->attach(zmq_errno => [] => 'int'); 1641 $ffi->attach(zmq_strerror => ['int'] => 'string'); 1642 1643 my $context = zmq_ctx_new(); 1644 zmq_ctx_set($context, ZMQ_IO_THREADS, 1); 1645 1646 my $socket1 = zmq_socket($context, ZMQ_REQ); 1647 zmq_connect($socket1, $endpoint); 1648 1649 my $socket2 = zmq_socket($context, ZMQ_REP); 1650 zmq_bind($socket2, $endpoint); 1651 1652 do { # send 1653 our $sent_message = "hello there"; 1654 my($pointer, $size) = scalar_to_buffer $sent_message; 1655 my $r = zmq_send($socket1, $pointer, $size, 0); 1656 die zmq_strerror(zmq_errno()) if $r == -1; 1657 }; 1658 1659 do { # recv 1660 my $msg_ptr = malloc 100; 1661 zmq_msg_init($msg_ptr); 1662 my $size = zmq_msg_recv($msg_ptr, $socket2, 0); 1663 die zmq_strerror(zmq_errno()) if $size == -1; 1664 my $data_ptr = zmq_msg_data($msg_ptr); 1665 my $recv_message = buffer_to_scalar $data_ptr, $size; 1666 print "recv_message = $recv_message\n"; 1667 }; 1668 1669B<Discussion>: ØMQ is a high-performance asynchronous messaging library. 1670There are a few things to note here. 1671 1672Firstly, sometimes there may be multiple versions of a library in the 1673wild and you may need to verify that the library on a system meets your 1674needs (alternatively you could support multiple versions and configure 1675your bindings dynamically). Here we use C<zmq_version> to ask libzmq 1676which version it is. 1677 1678C<zmq_version> returns the version number via three integer pointer 1679arguments, so we use the pointer to integer type: C<int *>. In order to 1680pass pointer types, we pass a reference. In this case it is a reference 1681to an undefined value, because zmq_version will write into the pointers 1682the output values, but you can also pass in references to integers, 1683floating point values and opaque pointer types. When the function 1684returns the C<$major> variable (and the others) has been updated and we 1685can use it to verify that it supports the API that we require. 1686 1687Notice that we define three aliases for the C<opaque> type: 1688C<zmq_context>, C<zmq_socket> and C<zmq_msg_t>. While this isn't 1689strictly necessary, since Platypus and C treat all three of these types 1690the same, it is useful form of documentation that helps describe the 1691functionality of the interface. 1692 1693Finally we attach the necessary functions, send and receive a message. 1694If you are interested, there is a fully fleshed out ØMQ Perl interface 1695implemented using FFI called L<ZMQ::FFI>. 1696 1697=head2 libarchive 1698 1699 use FFI::Platypus 1.00; 1700 use FFI::CheckLib qw( find_lib_or_exit ); 1701 1702 # This example uses FreeBSD's libarchive to list the contents of any 1703 # archive format that it suppors. We've also filled out a part of 1704 # the ArchiveWrite class that could be used for writing archive formats 1705 # supported by libarchive 1706 1707 my $ffi = FFI::Platypus->new( api => 1 ); 1708 $ffi->lib(find_lib_or_exit lib => 'archive'); 1709 $ffi->type('object(Archive)' => 'archive_t'); 1710 $ffi->type('object(ArchiveRead)' => 'archive_read_t'); 1711 $ffi->type('object(ArchiveWrite)' => 'archive_write_t'); 1712 $ffi->type('object(ArchiveEntry)' => 'archive_entry_t'); 1713 1714 package Archive; 1715 1716 # base class is "abstract" having no constructor or destructor 1717 1718 $ffi->mangler(sub { 1719 my($name) = @_; 1720 "archive_$name"; 1721 }); 1722 $ffi->attach( error_string => ['archive_t'] => 'string' ); 1723 1724 package ArchiveRead; 1725 1726 our @ISA = qw( Archive ); 1727 1728 $ffi->mangler(sub { 1729 my($name) = @_; 1730 "archive_read_$name"; 1731 }); 1732 1733 $ffi->attach( new => ['string'] => 'archive_read_t' ); 1734 $ffi->attach( [ free => 'DESTROY' ] => ['archive_t'] => 'void' ); 1735 $ffi->attach( support_filter_all => ['archive_t'] => 'int' ); 1736 $ffi->attach( support_format_all => ['archive_t'] => 'int' ); 1737 $ffi->attach( open_filename => ['archive_t','string','size_t'] => 'int' ); 1738 $ffi->attach( next_header2 => ['archive_t', 'archive_entry_t' ] => 'int' ); 1739 $ffi->attach( data_skip => ['archive_t'] => 'int' ); 1740 # ... define additional read methods 1741 1742 package ArchiveWrite; 1743 1744 our @ISA = qw( Archive ); 1745 1746 $ffi->mangler(sub { 1747 my($name) = @_; 1748 "archive_write_$name"; 1749 }); 1750 1751 $ffi->attach( new => ['string'] => 'archive_write_t' ); 1752 $ffi->attach( [ free => 'DESTROY' ] => ['archive_write_t'] => 'void' ); 1753 # ... define additional write methods 1754 1755 package ArchiveEntry; 1756 1757 $ffi->mangler(sub { 1758 my($name) = @_; 1759 "archive_entry_$name"; 1760 }); 1761 1762 $ffi->attach( new => ['string'] => 'archive_entry_t' ); 1763 $ffi->attach( [ free => 'DESTROY' ] => ['archive_entry_t'] => 'void' ); 1764 $ffi->attach( pathname => ['archive_entry_t'] => 'string' ); 1765 # ... define additional entry methods 1766 1767 package main; 1768 1769 use constant ARCHIVE_OK => 0; 1770 1771 # this is a Perl version of the C code here: 1772 # https://github.com/libarchive/libarchive/wiki/Examples#List_contents_of_Archive_stored_in_File 1773 1774 my $archive_filename = shift @ARGV; 1775 unless(defined $archive_filename) 1776 { 1777 print "usage: $0 archive.tar\n"; 1778 exit; 1779 } 1780 1781 my $archive = ArchiveRead->new; 1782 $archive->support_filter_all; 1783 $archive->support_format_all; 1784 1785 my $r = $archive->open_filename($archive_filename, 1024); 1786 die "error opening $archive_filename: ", $archive->error_string 1787 unless $r == ARCHIVE_OK; 1788 1789 my $entry = ArchiveEntry->new; 1790 1791 while($archive->next_header2($entry) == ARCHIVE_OK) 1792 { 1793 print $entry->pathname, "\n"; 1794 $archive->data_skip; 1795 } 1796 1797B<Discussion>: libarchive is the implementation of C<tar> for FreeBSD 1798provided as a library and available on a number of platforms. 1799 1800One interesting thing about libarchive is that it provides a kind of 1801object oriented interface via opaque pointers. This example creates an 1802abstract class C<Archive>, and concrete classes C<ArchiveWrite>, 1803C<ArchiveRead> and C<ArchiveEntry>. The concrete classes can even be 1804inherited from and extended just like any Perl classes because of the 1805way the custom types are implemented. We use Platypus's C<object> 1806type for this implementation, which is a wrapper around an C<opaque> 1807(can also be an integer) type that is blessed into a particular class. 1808 1809Another advanced feature of this example is that we define a mangler 1810to modify the symbol resolution for each class. This means we can do 1811this when we define a method for Archive: 1812 1813 $ffi->attach( support_filter_all => ['archive_t'] => 'int' ); 1814 1815Rather than this: 1816 1817 $ffi->attach( 1818 [ archive_read_support_filter_all => 'support_read_filter_all' ] => 1819 ['archive_t'] => 'int' ); 1820 ); 1821 1822=head2 unix open 1823 1824 use FFI::Platypus 1.00; 1825 1826 { 1827 package FD; 1828 1829 use constant O_RDONLY => 0; 1830 use constant O_WRONLY => 1; 1831 use constant O_RDWR => 2; 1832 1833 use constant IN => bless \do { my $in=0 }, __PACKAGE__; 1834 use constant OUT => bless \do { my $out=1 }, __PACKAGE__; 1835 use constant ERR => bless \do { my $err=2 }, __PACKAGE__; 1836 1837 my $ffi = FFI::Platypus->new( api => 1, lib => [undef]); 1838 1839 $ffi->type('object(FD,int)' => 'fd'); 1840 1841 $ffi->attach( [ 'open' => 'new' ] => [ 'string', 'int', 'mode_t' ] => 'fd' => sub { 1842 my($xsub, $class, $fn, @rest) = @_; 1843 my $fd = $xsub->($fn, @rest); 1844 die "error opening $fn $!" if $$fd == -1; 1845 $fd; 1846 }); 1847 1848 $ffi->attach( write => ['fd', 'string', 'size_t' ] => 'ssize_t' ); 1849 $ffi->attach( read => ['fd', 'string', 'size_t' ] => 'ssize_t' ); 1850 $ffi->attach( close => ['fd'] => 'int' ); 1851 } 1852 1853 my $fd = FD->new("$0", FD::O_RDONLY); 1854 1855 my $buffer = "\0" x 10; 1856 1857 while(my $br = $fd->read($buffer, 10)) 1858 { 1859 FD::OUT->write($buffer, $br); 1860 } 1861 1862 $fd->close; 1863 1864B<Discussion>: The Unix file system calls use an integer handle for 1865each open file. We can use the same C<object> type that we used 1866for libarchive above, except we let platypus know that the underlying 1867type is C<int> instead of C<opaque> (the latter being the default for 1868the C<object> type). Mainly just for demonstration since Perl has much 1869better IO libraries, but now we have an OO interface to the Unix IO 1870functions. 1871 1872=head2 bzip2 1873 1874 use FFI::Platypus 1.00; 1875 use FFI::CheckLib qw( find_lib_or_die ); 1876 use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar ); 1877 use FFI::Platypus::Memory qw( malloc free ); 1878 1879 my $ffi = FFI::Platypus->new( api => 1 ); 1880 $ffi->lib(find_lib_or_die lib => 'bz2'); 1881 1882 $ffi->attach( 1883 [ BZ2_bzBuffToBuffCompress => 'compress' ] => [ 1884 'opaque', # dest 1885 'unsigned int *', # dest length 1886 'opaque', # source 1887 'unsigned int', # source length 1888 'int', # blockSize100k 1889 'int', # verbosity 1890 'int', # workFactor 1891 ] => 'int', 1892 sub { 1893 my $sub = shift; 1894 my($source,$source_length) = scalar_to_buffer $_[0]; 1895 my $dest_length = int(length($source)*1.01) + 1 + 600; 1896 my $dest = malloc $dest_length; 1897 my $r = $sub->($dest, \$dest_length, $source, $source_length, 9, 0, 30); 1898 die "bzip2 error $r" unless $r == 0; 1899 my $compressed = buffer_to_scalar($dest, $dest_length); 1900 free $dest; 1901 $compressed; 1902 }, 1903 ); 1904 1905 $ffi->attach( 1906 [ BZ2_bzBuffToBuffDecompress => 'decompress' ] => [ 1907 'opaque', # dest 1908 'unsigned int *', # dest length 1909 'opaque', # source 1910 'unsigned int', # source length 1911 'int', # small 1912 'int', # verbosity 1913 ] => 'int', 1914 sub { 1915 my $sub = shift; 1916 my($source, $source_length) = scalar_to_buffer $_[0]; 1917 my $dest_length = $_[1]; 1918 my $dest = malloc $dest_length; 1919 my $r = $sub->($dest, \$dest_length, $source, $source_length, 0, 0); 1920 die "bzip2 error $r" unless $r == 0; 1921 my $decompressed = buffer_to_scalar($dest, $dest_length); 1922 free $dest; 1923 $decompressed; 1924 }, 1925 ); 1926 1927 my $original = "hello compression world\n"; 1928 my $compressed = compress($original); 1929 print decompress($compressed, length $original); 1930 1931B<Discussion>: bzip2 is a compression library. For simple one shot 1932attempts at compression/decompression when you expect the original and 1933the result to fit within memory it provides two convenience functions 1934C<BZ2_bzBuffToBuffCompress> and C<BZ2_bzBuffToBuffDecompress>. 1935 1936The first four arguments of both of these C functions are identical, and 1937represent two buffers. One buffer is the source, the second is the 1938destination. For the destination, the length is passed in as a pointer 1939to an integer. On input this integer is the size of the destination 1940buffer, and thus the maximum size of the compressed or decompressed 1941data. When the function returns the actual size of compressed or 1942compressed data is stored in this integer. 1943 1944This is normal stuff for C, but in Perl our buffers are scalars and they 1945already know how large they are. In this sort of situation, wrapping 1946the C function in some Perl code can make your interface a little more 1947Perl like. In order to do this, just provide a code reference as the 1948last argument to the L</attach> method. The first argument to this 1949wrapper will be a code reference to the C function. The Perl arguments 1950will come in after that. This allows you to modify / convert the 1951arguments to conform to the C API. What ever value you return from the 1952wrapper function will be returned back to the original caller. 1953 1954=head2 The Win32 API 1955 1956 use utf8; 1957 use FFI::Platypus 1.00; 1958 1959 my $ffi = FFI::Platypus->new( 1960 api => 1, 1961 lib => [undef], 1962 ); 1963 1964 # see FFI::Platypus::Lang::Win32 1965 $ffi->lang('Win32'); 1966 1967 # Send a Unicode string to the Windows API MessageBoxW function. 1968 use constant MB_OK => 0x00000000; 1969 use constant MB_DEFAULT_DESKTOP_ONLY => 0x00020000; 1970 $ffi->attach( [MessageBoxW => 'MessageBox'] => [ 'HWND', 'LPCWSTR', 'LPCWSTR', 'UINT'] => 'int' ); 1971 MessageBox(undef, "I ❤️ Platypus", "Confession", MB_OK|MB_DEFAULT_DESKTOP_ONLY); 1972 1973B<Discussion>: The API used by Microsoft Windows present some unique 1974challenges. On 32 bit systems a different ABI is used than what is 1975used by the standard C library. It also provides a rats nest of 1976type aliases. Finally if you want to talk Unicode to any of the 1977Windows API you will need to use C<UTF-16LE> instead of C<utf-8> 1978which is native to Perl. (The Win32 API refers to these as 1979C<LPWSTR> and C<LPCWSTR> types). As much as possible the Win32 1980"language" plugin attempts to handle this transparently. For more 1981details see L<FFI::Platypus::Lang::Win32>. 1982 1983=head2 bundle your own code 1984 1985C<ffi/foo.c>: 1986 1987 #include <ffi_platypus_bundle.h> 1988 #include <string.h> 1989 1990 typedef struct { 1991 char *name; 1992 int value; 1993 } foo_t; 1994 1995 foo_t* 1996 foo__new(const char *class_name, const char *name, int value) 1997 { 1998 (void)class_name; 1999 foo_t *self = malloc( sizeof( foo_t ) ); 2000 self->name = strdup(name); 2001 self->value = value; 2002 return self; 2003 } 2004 2005 const char * 2006 foo__name(foo_t *self) 2007 { 2008 return self->name; 2009 } 2010 2011 int 2012 foo__value(foo_t *self) 2013 { 2014 return self->value; 2015 } 2016 2017 void 2018 foo__DESTROY(foo_t *self) 2019 { 2020 free(self->name); 2021 free(self); 2022 } 2023 2024C<lib/Foo.pm>: 2025 2026 package Foo; 2027 2028 use strict; 2029 use warnings; 2030 use FFI::Platypus 1.00; 2031 2032 { 2033 my $ffi = FFI::Platypus->new( api => 1 ); 2034 2035 $ffi->type('object(Foo)' => 'foo_t'); 2036 $ffi->mangler(sub { 2037 my $name = shift; 2038 $name =~ s/^/foo__/; 2039 $name; 2040 }); 2041 2042 $ffi->bundle; 2043 2044 $ffi->attach( new => [ 'string', 'string', 'int' ] => 'foo_t' ); 2045 $ffi->attach( name => [ 'foo_t' ] => 'string' ); 2046 $ffi->attach( value => [ 'foo_t' ] => 'int' ); 2047 $ffi->attach( DESTROY => [ 'foo_t' ] => 'void' ); 2048 } 2049 2050 1; 2051 2052You can bundle your own C (or other compiled language) code with your 2053Perl extension. Sometimes this is helpful for smoothing over the 2054interface of a C library which is not very FFI friendly. Sometimes 2055you may want to write some code in C for a tight loop. Either way, 2056you can do this with the Platypus bundle interface. See 2057L<FFI::Platypus::Bundle> for more details. 2058 2059Also related is the bundle constant interface, which allows you to 2060define Perl constants in C space. See L<FFI::Platypus::Constant> 2061for details. 2062 2063=head1 FAQ 2064 2065=head2 How do I get constants defined as macros in C header files 2066 2067This turns out to be a challenge for any language calling into C, which 2068frequently uses C<#define> macros to define constants like so: 2069 2070 #define FOO_STATIC 1 2071 #define FOO_DYNAMIC 2 2072 #define FOO_OTHER 3 2073 2074As macros are expanded and their definitions are thrown away by the C pre-processor 2075there isn't any way to get the name/value mappings from the compiled dynamic 2076library. 2077 2078You can manually create equivalent constants in your Perl source: 2079 2080 use constant FOO_STATIC => 1; 2081 use constant FOO_DYNAMIC => 2; 2082 use constant FOO_OTHER => 3; 2083 2084If there are a lot of these types of constants you might want to consider using 2085a tool (L<Convert::Binary::C> can do this) that can extract the constants for you. 2086 2087See also the "Integer constants" example in L<FFI::Platypus::Type>. 2088 2089You can also use the new Platypus bundle interface to define Perl constants 2090from C space. This is more reliable, but does require a compiler at install 2091time. It is recommended mainly for writing bindings against libraries that 2092have constants that can vary widely from platform to platform. See 2093L<FFI::Platypus::Constant> for details. 2094 2095=head2 What about enums? 2096 2097The C enum types are integers. The underlying type is up to the platform, so 2098Platypus provides C<enum> and C<senum> types for unsigned and singed enums 2099respectively. At least some compilers treat signed and unsigned enums as 2100different types. The enum I<values> are essentially the same as macro constants 2101described above from an FFI perspective. Thus the process of defining enum values 2102is identical to the process of defining macro constants in Perl. 2103 2104For more details on enumerated types see L<FFI::Platypus::Type/"Enum types">. 2105 2106There is also a type plugin (L<FFI::Platypus::Type::Enum>) that can be helpful 2107in writing interfaces that use enums. 2108 2109=head2 Memory leaks 2110 2111There are a couple places where memory is allocated, but never deallocated that may 2112look like memory leaks by tools designed to find memory leaks like valgrind. This 2113memory is intended to be used for the lifetime of the perl process so there normally 2114this isn't a problem unless you are embedding a Perl interpreter which doesn't closely 2115match the lifetime of your overall application. 2116 2117Specifically: 2118 2119=over 4 2120 2121=item type cache 2122 2123some types are cached and not freed. These are needed as long as there are FFI 2124functions that could be called. 2125 2126=item attached functions 2127 2128Attaching a function as an xsub will definitely allocate memory that won't be freed 2129because the xsub could be called at any time, including in C<END> blocks. 2130 2131=back 2132 2133The Platypus team plans on adding a hook to free some of this "leaked" memory 2134for use cases where Perl and Platypus are embedded in a larger application 2135where the lifetime of the Perl process is significantly smaller than the 2136overall lifetime of the whole process. 2137 2138=head2 I get seg faults on some platforms but not others with a library using pthreads. 2139 2140On some platforms, Perl isn't linked with C<libpthreads> if Perl threads are not 2141enabled. On some platforms this doesn't seem to matter, C<libpthreads> can be 2142loaded at runtime without much ill-effect. (Linux from my experience doesn't seem 2143to mind one way or the other). Some platforms are not happy about this, and about 2144the only thing that you can do about it is to build Perl such that it links with 2145C<libpthreads> even if it isn't a threaded Perl. 2146 2147This is not really an FFI issue, but a Perl issue, as you will have the same 2148problem writing XS code for the such libraries. 2149 2150=head2 Doesn't work on Perl 5.10.0. 2151 2152I try as best as possible to support the same range of Perls as the Perl toolchain. 2153That means all the way back to 5.8.1. Unfortunately, 5.10.0 seems to have a problem 2154that is difficult to diagnose. Patches to fix are welcome, if you want to help 2155out on this, please see: 2156 2157L<https://github.com/PerlFFI/FFI-Platypus/issues/68> 2158 2159Since this is an older buggy version of Perl it is recommended that you instead 2160upgrade to 5.10.1 or later. 2161 2162=head1 CAVEATS 2163 2164Platypus and Native Interfaces like libffi rely on the availability of 2165dynamic libraries. Things not supported include: 2166 2167=over 4 2168 2169=item Systems that lack dynamic library support 2170 2171Like MS-DOS 2172 2173=item Systems that are not supported by libffi 2174 2175Like OpenVMS 2176 2177=item Languages that do not support using dynamic libraries from other languages 2178 2179Like older versions of Google's Go. This is a problem for C / XS code as well. 2180 2181=item Languages that do not compile to machine code 2182 2183Like .NET based languages and Java. 2184 2185=back 2186 2187The documentation has a bias toward using FFI / Platypus with C. This 2188is my fault, as my background in mainly in C/C++ programmer (when I am 2189not writing Perl). In many places I use "C" as a short form for "any 2190language that can generate machine code and is callable from C". I 2191welcome pull requests to the Platypus core to address this issue. In an 2192attempt to ease usage of Platypus by non C programmers, I have written a 2193number of foreign language plugins for various popular languages (see 2194the SEE ALSO below). These plugins come with examples specific to those 2195languages, and documentation on common issues related to using those 2196languages with FFI. In most cases these are available for easy adoption 2197for those with the know-how or the willingness to learn. If your 2198language doesn't have a plugin YET, that is just because you haven't 2199written it yet. 2200 2201=head1 SUPPORT 2202 2203IRC: #native on irc.perl.org 2204 2205L<(click for instant chat room login)|http://chat.mibbit.com/#native@irc.perl.org> 2206 2207If something does not work the way you think it should, or if you have a 2208feature request, please open an issue on this project's GitHub Issue 2209tracker: 2210 2211L<https://github.com/perlFFI/FFI-Platypus/issues> 2212 2213=head1 CONTRIBUTING 2214 2215If you have implemented a new feature or fixed a bug then you may make a 2216pull request on this project's GitHub repository: 2217 2218L<https://github.com/PerlFFI/FFI-Platypus/pulls> 2219 2220This project is developed using L<Dist::Zilla>. The project's git 2221repository also comes with the C<Makefile.PL> file necessary 2222for building, testing (and even installing if necessary) without 2223L<Dist::Zilla>. Please keep in mind though that these files are 2224generated so if changes need to be made to those files they should be 2225done through the project's C<dist.ini> file. If you do use 2226L<Dist::Zilla> and already have the necessary plugins installed, then I 2227encourage you to run C<dzil test> before making any pull requests. This 2228is not a requirement, however, I am happy to integrate especially 2229smaller patches that need tweaking to fit the project standards. I may 2230push back and ask you to write a test case or alter the formatting of a 2231patch depending on the amount of time I have and the amount of code that 2232your patch touches. 2233 2234This project's GitHub issue tracker listed above is not Write-Only. If 2235you want to contribute then feel free to browse through the existing 2236issues and see if there is something you feel you might be good at and 2237take a whack at the problem. I frequently open issues myself that I 2238hope will be accomplished by someone in the future but do not have time 2239to immediately implement myself. 2240 2241Another good area to help out in is documentation. I try to make sure 2242that there is good document coverage, that is there should be 2243documentation describing all the public features and warnings about 2244common pitfalls, but an outsider's or alternate view point on such 2245things would be welcome; if you see something confusing or lacks 2246sufficient detail I encourage documentation only pull requests to 2247improve things. 2248 2249The Platypus distribution comes with a test library named C<libtest> 2250that is normally automatically built by C<./Build test>. If you prefer 2251to use C<prove> or run tests directly, you can use the C<./Build 2252libtest> command to build it. Example: 2253 2254 % perl Makefile.PL 2255 % make 2256 % make ffi-test 2257 % prove -bv t 2258 # or an individual test 2259 % perl -Mblib t/ffi_platypus_memory.t 2260 2261The build process also respects these environment variables: 2262 2263=over 4 2264 2265=item FFI_PLATYPUS_DEBUG_FAKE32 2266 2267When building Platypus on 32 bit Perls, it will use the L<Math::Int64> C 2268API and make L<Math::Int64> a prerequisite. Setting this environment 2269variable will force Platypus to build with both of those options on a 64 2270bit Perl as well. 2271 2272 % env FFI_PLATYPUS_DEBUG_FAKE32=1 perl Makefile.PL 2273 DEBUG_FAKE32: 2274 + making Math::Int64 a prereq 2275 + Using Math::Int64's C API to manipulate 64 bit values 2276 Generating a Unix-style Makefile 2277 Writing Makefile for FFI::Platypus 2278 Writing MYMETA.yml and MYMETA.json 2279 % 2280 2281=item FFI_PLATYPUS_NO_ALLOCA 2282 2283Platypus uses the non-standard and somewhat controversial C function 2284C<alloca> by default on platforms that support it. I believe that 2285Platypus uses it responsibly to allocate small amounts of memory for 2286argument type parameters, and does not use it to allocate large 2287structures like arrays or buffers. If you prefer not to use C<alloca> 2288despite these precautions, then you can turn its use off by setting this 2289environment variable when you run C<Makefile.PL>: 2290 2291 helix% env FFI_PLATYPUS_NO_ALLOCA=1 perl Makefile.PL 2292 NO_ALLOCA: 2293 + alloca() will not be used, even if your platform supports it. 2294 Generating a Unix-style Makefile 2295 Writing Makefile for FFI::Platypus 2296 Writing MYMETA.yml and MYMETA.json 2297 2298=item V 2299 2300When building platypus may hide some of the excessive output when 2301probing and building, unless you set C<V> to a true value. 2302 2303 % env V=1 perl Makefile.PL 2304 % make V=1 2305 ... 2306 2307=back 2308 2309=head2 Coding Guidelines 2310 2311=over 4 2312 2313=item 2314 2315Do not hesitate to make code contribution. Making useful contributions 2316is more important than following byzantine bureaucratic coding 2317regulations. We can always tweak things later. 2318 2319=item 2320 2321Please make an effort to follow existing coding style when making pull 2322requests. 2323 2324=item 2325 2326Platypus supports all production Perl releases since 5.8.1. For that 2327reason, please do not introduce any code that requires a newer version 2328of Perl. 2329 2330=back 2331 2332=head2 Performance Testing 2333 2334As Mark Twain was fond of saying there are four types of lies: lies, 2335damn lies, statistics and benchmarks. That being said, it can sometimes 2336be helpful to compare the runtime performance of Platypus if you are 2337making significant changes to the Platypus Core. For that I use 2338`FFI-Performance`, which can be found in my GitHub repository here: 2339 2340=over 4 2341 2342=item L<https://github.com/PerlFFI/FFI-Performance> 2343 2344=back 2345 2346=head2 System integrators 2347 2348This distribution uses L<Alien::FFI> in fallback mode, meaning if 2349the system doesn't provide C<pkg-config> and C<libffi> it will attempt 2350to download C<libffi> and build it from source. If you are including 2351Platypus in a larger system (for example a Linux distribution) you 2352only need to make sure to declare C<pkg-config> or C<pkgconf> and 2353the development package for C<libffi> as prereqs for this module. 2354 2355=head1 SEE ALSO 2356 2357=over 4 2358 2359=item L<NativeCall> 2360 2361Promising interface to Platypus inspired by Raku. 2362 2363=item L<FFI::Platypus::Type> 2364 2365Type definitions for Platypus. 2366 2367=item L<FFI::Platypus::Record> 2368 2369Define structured data records (C "structs") for use with 2370Platypus. 2371 2372=item L<FFI::C> 2373 2374Another interface for defining structured data records for use 2375with Platypus. Its advantage over L<FFI::Platypus::Record> is 2376that it supports C<union>s and nested data structures. Its 2377disadvantage is that it doesn't support passing C<struct>s 2378by-value. 2379 2380=item L<FFI::Platypus::API> 2381 2382The custom types API for Platypus. 2383 2384=item L<FFI::Platypus::Memory> 2385 2386Memory functions for FFI. 2387 2388=item L<FFI::CheckLib> 2389 2390Find dynamic libraries in a portable way. 2391 2392=item L<FFI::TinyCC> 2393 2394JIT compiler for FFI. 2395 2396=item L<FFI::Platypus::Lang::C> 2397 2398Documentation and tools for using Platypus with the C programming 2399language 2400 2401=item L<FFI::Platypus::Lang::CPP> 2402 2403Documentation and tools for using Platypus with the C++ programming 2404language 2405 2406=item L<FFI::Platypus::Lang::Fortran> 2407 2408Documentation and tools for using Platypus with Fortran 2409 2410=item L<FFI::Platypus::Lang::Go> 2411 2412Documentation and tools for using Platypus with Go 2413 2414=item L<FFI::Platypus::Lang::Pascal> 2415 2416Documentation and tools for using Platypus with Free Pascal 2417 2418=item L<FFI::Platypus::Lang::Rust> 2419 2420Documentation and tools for using Platypus with the Rust programming 2421language 2422 2423=item L<FFI::Platypus::Lang::ASM> 2424 2425Documentation and tools for using Platypus with the Assembly 2426 2427=item L<FFI::Platypus::Lang::Win32> 2428 2429Documentation and tools for using Platypus with the Win32 API. 2430 2431=item L<Wasm> and L<Wasm::Wasmtime> 2432 2433Modules for writing WebAssembly bindings in Perl. This allows you to call 2434functions written in any language supported by WebAssembly. These modules 2435are also implemented using Platypus. 2436 2437=item L<Convert::Binary::C> 2438 2439A great interface for decoding C data structures, including C<struct>s, 2440C<enum>s, C<#define>s and more. 2441 2442=item L<pack and unpack|perlpacktut> 2443 2444Native to Perl functions that can be used to decode C C<struct> types. 2445 2446=item L<C::Scan> 2447 2448This module can extract constants and other useful objects from C header 2449files that may be relevant to an FFI application. One downside is that 2450its use may require development packages to be installed. 2451 2452=item L<Win32::API> 2453 2454Microsoft Windows specific FFI style interface. 2455 2456=item L<Ctypes|https://gitorious.org/perl-ctypes> 2457 2458Ctypes was intended as a FFI style interface for Perl, but was never 2459part of CPAN, and at least the last time I tried it did not work with 2460recent versions of Perl. 2461 2462=item L<FFI> 2463 2464Older, simpler, less featureful FFI. It used to be implemented 2465using FSF's C<ffcall>. Because C<ffcall> has been unsupported for 2466some time, I reimplemented this module using L<FFI::Platypus>. 2467 2468=item L<C::DynaLib> 2469 2470Another FFI for Perl that doesn't appear to have worked for a long time. 2471 2472=item L<C::Blocks> 2473 2474Embed a tiny C compiler into your Perl scripts. 2475 2476=item L<Alien::FFI> 2477 2478Provides libffi for Platypus during its configuration and build stages. 2479 2480=item L<P5NCI> 2481 2482Yet another FFI like interface that does not appear to be supported or 2483under development anymore. 2484 2485=back 2486 2487=head1 ACKNOWLEDGMENTS 2488 2489In addition to the contributors mentioned below, I would like to 2490acknowledge Brock Wilcox (AWWAIID) and Meredith Howard (MHOWARD) whose 2491work on C<FFI::Sweet> not only helped me get started with FFI but 2492significantly influenced the design of Platypus. 2493 2494Dan Book, who goes by Grinnz on IRC for answering user questions about 2495FFI and Platypus. 2496 2497In addition I'd like to thank Alessandro Ghedini (ALEXBIO) whose work 2498on another Perl FFI library helped drive some of the development ideas 2499for L<FFI::Platypus>. 2500 2501=head1 AUTHOR 2502 2503Author: Graham Ollis E<lt>plicease@cpan.orgE<gt> 2504 2505Contributors: 2506 2507Bakkiaraj Murugesan (bakkiaraj) 2508 2509Dylan Cali (calid) 2510 2511pipcet 2512 2513Zaki Mughal (zmughal) 2514 2515Fitz Elliott (felliott) 2516 2517Vickenty Fesunov (vyf) 2518 2519Gregor Herrmann (gregoa) 2520 2521Shlomi Fish (shlomif) 2522 2523Damyan Ivanov 2524 2525Ilya Pavlov (Ilya33) 2526 2527Petr Písař (ppisar) 2528 2529Mohammad S Anwar (MANWAR) 2530 2531Håkon Hægland (hakonhagland, HAKONH) 2532 2533Meredith (merrilymeredith, MHOWARD) 2534 2535Diab Jerius (DJERIUS) 2536 2537Eric Brine (IKEGAMI) 2538 2539szTheory 2540 2541José Joaquín Atria (JJATRIA) 2542 2543Pete Houston (openstrike, HOUSTON) 2544 2545=head1 COPYRIGHT AND LICENSE 2546 2547This software is copyright (c) 2015,2016,2017,2018,2019,2020 by Graham Ollis. 2548 2549This is free software; you can redistribute it and/or modify it under 2550the same terms as the Perl 5 programming language system itself. 2551 2552=cut 2553