Debian Codegraph @

lib/FFI/Platypus.pm

raw
1 package FFI::Platypus;
2
3 use strict;
4 use warnings;
5 use 5.008004;
6 use Carp qw( croak );
7 use FFI::Platypus::Function;
8 use FFI::Platypus::Type;
9
10 # ABSTRACT: Write Perl bindings to non-Perl libraries with FFI. No XS required.
11 our $VERSION = '2.12'; # 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
25 our @CARP_NOT = qw( FFI::Platypus::Declare FFI::Platypus::Record );
26
27 require XSLoader;
28 XSLoader::load(
29 'FFI::Platypus', $FFI::Platypus::VERSION || 0
30 );
31
32
33 sub 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 elsif($experimental == 2)
61 {
62 Carp::croak("Please do not use the experimental version of api = 2, instead require FFI::Platypus 2.00 or better");
63 }
64
65 if(defined $api && $api > 2 && $experimental != $api)
66 {
67 Carp::cluck("Enabling development API version $api prior to FFI::Platypus $api.00");
68 }
69
70 my $tp;
71
72 if($api == 0)
73 {
74 $tp = 'Version0';
75 }
76 elsif($api == 1)
77 {
78 $tp = 'Version1';
79 }
80 elsif($api == 2)
81 {
82 $tp = 'Version2';
83 }
84 else
85 {
86 Carp::croak("API version $api not (yet) implemented");
87 }
88
89 require "FFI/Platypus/TypeParser/$tp.pm";
90 $tp = "FFI::Platypus::TypeParser::$tp";
91
92 my $self = bless {
93 lib => \@lib,
94 lang => '',
95 handles => {},
96 abi => -1,
97 api => $api,
98 tp => $tp->new,
99 fini => [],
100 ignore_not_found => defined $args{ignore_not_found} ? $args{ignore_not_found} : 0,
101 }, $class;
102
103 $self->lang($args{lang} || 'C');
104
105 $self;
106 }
107
108 sub _lang_class ($)
109 {
110 my($lang) = @_;
111 my $class = $lang =~ m/^=(.*)$/ ? $1 : "FFI::Platypus::Lang::$lang";
112 unless($class->can('native_type_map'))
113 {
114 my $pm = "$class.pm";
115 $pm =~ s/::/\//g;
116 require $pm;
117 }
118 croak "$class does not provide native_type_map method"
119 unless $class->can("native_type_map");
120 $class;
121 }
122
123
124 sub lib
125 {
126 my($self, @new) = @_;
127
128 if(@new)
129 {
130 push @{ $self->{lib} }, map { ref $_ eq 'CODE' ? $_->() : $_ } @new;
131 delete $self->{mangler};
132 }
133
134 @{ $self->{lib} };
135 }
136
137
138 sub ignore_not_found
139 {
140 my($self, $value) = @_;
141
142 if(defined $value)
143 {
144 $self->{ignore_not_found} = $value;
145 }
146
147 $self->{ignore_not_found};
148 }
149
150
151 sub lang
152 {
153 my($self, $value) = @_;
154
155 if(defined $value && $value ne $self->{lang})
156 {
157 $self->{lang} = $value;
158 my $class = _lang_class($self->{lang});
159 $self->abi($class->abi) if $class->can('abi');
160
161 {
162 my %type_map;
163 my $map = $class->native_type_map(
164 $self->{api} > 0
165 ? (api => $self->{api})
166 : ()
167 );
168 foreach my $key (keys %$map)
169 {
170 my $value = $map->{$key};
171 next unless $self->{tp}->have_type($value);
172 $type_map{$key} = $value;
173 }
174 $type_map{$_} = $_ for grep { $self->{tp}->have_type($_) }
175 qw( void sint8 uint8 sint16 uint16 sint32 uint32 sint64 uint64 float double string opaque
176 longdouble complex_float complex_double );
177 $type_map{pointer} = 'opaque' if $self->{tp}->isa('FFI::Platypus::TypeParser::Version0');
178 $self->{tp}->type_map(\%type_map);
179 }
180
181 $class->load_custom_types($self) if $class->can('load_custom_types');
182 }
183
184 $self->{lang};
185 }
186
187
188 sub api { shift->{api} }
189
190
191 sub type
192 {
193 my($self, $name, $alias) = @_;
194 croak "usage: \$ffi->type(name => alias) (alias is optional)" unless defined $self && defined $name;
195
196 $self->{tp}->check_alias($alias) if defined $alias;
197 my $type = $self->{tp}->parse($name);
198 $self->{tp}->set_alias($alias, $type) if defined $alias;
199
200 $self;
201 }
202
203
204 sub custom_type
205 {
206 my($self, $alias, $cb) = @_;
207
208 my $argument_count = $cb->{argument_count} || 1;
209
210 croak "argument_count must be >= 1"
211 unless $argument_count >= 1;
212
213 croak "Usage: \$ffi->custom_type(\$alias, { ... })"
214 unless defined $alias && ref($cb) eq 'HASH';
215
216 croak "must define at least one of native_to_perl, perl_to_native, or perl_to_native_post"
217 unless defined $cb->{native_to_perl} || defined $cb->{perl_to_native} || defined $cb->{perl_to_native_post};
218
219 $self->{tp}->check_alias($alias);
220
221 my $type = $self->{tp}->create_type_custom(
222 $cb->{native_type},
223 $cb->{perl_to_native},
224 $cb->{native_to_perl},
225 $cb->{perl_to_native_post},
226 $argument_count,
227 );
228
229 $self->{tp}->set_alias($alias, $type);
230
231 $self;
232 }
233
234
235 sub load_custom_type
236 {
237 my($self, $name, $alias, @type_args) = @_;
238
239 croak "usage: \$ffi->load_custom_type(\$name, \$alias, ...)"
240 unless defined $name && defined $alias;
241
242 $name = "FFI::Platypus::Type$name" if $name =~ /^::/;
243 $name = "FFI::Platypus::Type::$name" unless $name =~ /::/;
244
245 unless($name->can("ffi_custom_type_api_1"))
246 {
247 my $pm = "$name.pm";
248 $pm =~ s/::/\//g;
249 eval { require $pm };
250 warn $@ if $@;
251 }
252
253 unless($name->can("ffi_custom_type_api_1"))
254 {
255 croak "$name does not appear to conform to the custom type API";
256 }
257
258 my $cb = $name->ffi_custom_type_api_1($self, @type_args);
259 $self->custom_type($alias => $cb);
260
261 $self;
262 }
263
264
265 sub types
266 {
267 my($self) = @_;
268 $self = $self->new unless ref $self && eval { $self->isa('FFI::Platypus') };
269 sort $self->{tp}->list_types;
270 }
271
272
273 sub type_meta
274 {
275 my($self, $name) = @_;
276 $self = $self->new unless ref $self && eval { $self->isa('FFI::Platypus') };
277 $self->{tp}->parse($name)->meta;
278 }
279
280
281 sub mangler
282 {
283 my($self, $sub) = @_;
284 $self->{mangler} = $self->{mymangler} = $sub;
285 }
286
287
288 sub function
289 {
290 my $wrapper;
291 $wrapper = pop if ref $_[-1] eq 'CODE';
292
293 croak "usage \$ffi->function( \$name, \\\@arguments, [\\\@var_args], [\$return_type])" unless @_ >= 3 && @_ <= 6;
294
295 my $self = shift;
296 my $name = shift;
297 my $fixed_args = shift;
298 my $var_args;
299 $var_args = shift if defined $_[0] && ref($_[0]) eq 'ARRAY';
300 my $ret = shift;
301 $ret = 'void' unless defined $ret;
302
303 # special case: treat a single void argument type as an empty list of
304 # arguments, a la olde timey C compilers.
305 if( (!defined $var_args) && @$fixed_args == 1 && $fixed_args->[0] eq 'void' )
306 {
307 $fixed_args = [];
308 }
309
310 my $fixed_arg_count = defined $var_args ? scalar(@$fixed_args) : -1;
311
312 my @args = map { $self->{tp}->parse($_) || croak "unknown type: $_" } @$fixed_args;
313 if($var_args)
314 {
315 push @args, map {
316 my $type = $self->{tp}->parse($_);
317 # https://github.com/PerlFFI/FFI-Platypus/issues/323
318 $type->type_code == 67 ? $self->{tp}->parse('double') : $type
319 } @$var_args;
320 }
321
322 $ret = $self->{tp}->parse($ret) || croak "unknown type: $ret";
323 my $address = $name =~ /^-?[0-9]+$/ ? $name : $self->find_symbol($name);
324 croak "unable to find $name" unless defined $address || $self->ignore_not_found;
325 return unless defined $address;
326 $address = @args > 0 ? _cast1() : _cast0() if $address == 0;
327 my $function = FFI::Platypus::Function::Function->new($self, $address, $self->{abi}, $fixed_arg_count, $ret, @args);
328 $wrapper
329 ? FFI::Platypus::Function::Wrapper->new($function, $wrapper)
330 : $function;
331 }
332
333 sub _function_meta
334 {
335 # NOTE: may be upgraded to a documented function one day,
336 # but shouldn't be used externally as we will rename it
337 # if that happens.
338 my($self, $name, $meta, $args, $ret) = @_;
339 $args = ['opaque','int',@$args];
340 $self->function(
341 $name, $args, $ret, sub {
342 my $xsub = shift;
343 $xsub->($meta, scalar(@_), @_);
344 },
345 );
346 }
347
348
349 sub attach
350 {
351 my $wrapper;
352 $wrapper = pop if ref $_[-1] eq 'CODE';
353
354 my $self = shift;
355 my $name = shift;
356 my $args = shift;
357 my $varargs;
358 $varargs = shift if defined $_[0] && ref($_[0]) eq 'ARRAY';
359 my $ret = shift;
360 my $proto = shift;
361
362 $ret = 'void' unless defined $ret;
363
364 my($c_name, $perl_name) = ref($name) ? @$name : ($name, $name);
365
366 croak "you tried to provide a perl name that looks like an address"
367 if $perl_name =~ /^-?[0-9]+$/;
368
369 my $function = $varargs
370 ? $self->function($c_name, $args, $varargs, $ret, $wrapper)
371 : $self->function($c_name, $args, $ret, $wrapper);
372
373 if(defined $function)
374 {
375 $function->attach($perl_name, $proto);
376 }
377
378 $self;
379 }
380
381
382 sub closure
383 {
384 my($self, $coderef) = @_;
385 return undef unless defined $coderef;
386 croak "not a coderef" unless ref $coderef eq 'CODE';
387 require FFI::Platypus::Closure;
388 FFI::Platypus::Closure->new($coderef);
389 }
390
391
392 sub cast
393 {
394 $_[0]->function(0 => [$_[1]] => $_[2])->call($_[3]);
395 }
396
397
398 sub attach_cast
399 {
400 my($self, $name, $type1, $type2, $wrapper) = @_;
401 my $caller = caller;
402 $name = join '::', $caller, $name unless $name =~ /::/;
403 if(defined $wrapper && ref($wrapper) eq 'CODE')
404 {
405 $self->attach([0 => $name] => [$type1] => $type2 => '$', $wrapper);
406 }
407 else
408 {
409 $self->attach([0 => $name] => [$type1] => $type2 => '$');
410 }
411 $self;
412 }
413
414
415 sub sizeof
416 {
417 my($self,$name) = @_;
418 ref $self
419 ? $self->{tp}->parse($name)->sizeof
420 : $self->new->sizeof($name);
421 }
422
423
424 sub alignof
425 {
426 my($self, $name) = @_;
427 ref $self
428 ? $self->{tp}->parse($name)->alignof
429 : $self->new->alignof($name);
430 }
431
432
433 sub kindof
434 {
435 my($self, $name) = @_;
436 ref $self
437 ? $self->{tp}->parse($name)->kindof
438 : $self->new->kindof($name);
439 }
440
441
442 sub countof
443 {
444 my($self, $name) = @_;
445 ref $self
446 ? $self->{tp}->parse($name)->countof
447 : $self->new->countof($name);
448 }
449
450
451 sub def
452 {
453 my $self = shift;
454 my $package = shift || caller;
455 my $type = shift;
456 if(@_)
457 {
458 $self->type($type);
459 $self->{def}->{$package}->{$type} = shift;
460 }
461 $self->{def}->{$package}->{$type};
462 }
463
464
465 sub unitof
466 {
467 my($self, $name) = @_;
468 ref $self
469 ? $self->{tp}->parse($name)->unitof
470 : $self->new->unitof($name);
471 }
472
473
474 sub find_lib
475 {
476 my $self = shift;
477 require FFI::CheckLib;
478 $self->lib(FFI::CheckLib::find_lib(@_));
479 $self;
480 }
481
482
483 sub find_symbol
484 {
485 my($self, $name) = @_;
486
487 $self->{mangler} ||= $self->{mymangler};
488
489 unless(defined $self->{mangler})
490 {
491 my $class = _lang_class($self->{lang});
492 if($class->can('mangler'))
493 {
494 $self->{mangler} = $class->mangler($self->lib);
495 }
496 else
497 {
498 $self->{mangler} = sub { $_[0] };
499 }
500 }
501
502 foreach my $path (@{ $self->{lib} })
503 {
504 my $handle = do { no warnings; $self->{handles}->{$path||0} } || FFI::Platypus::DL::dlopen($path, FFI::Platypus::DL::RTLD_PLATYPUS_DEFAULT());
505 unless($handle)
506 {
507 warn "warning: error loading $path: ", FFI::Platypus::DL::dlerror()
508 if $self->{api} > 0 || $ENV{FFI_PLATYPUS_DLERROR};
509 next;
510 }
511 my $address = FFI::Platypus::DL::dlsym($handle, $self->{mangler}->($name));
512 if($address)
513 {
514 $self->{handles}->{$path||0} = $handle;
515 return $address;
516 }
517 else
518 {
519 FFI::Platypus::DL::dlclose($handle) unless $self->{handles}->{$path||0};
520 }
521 }
522 return;
523 }
524
525
526 sub bundle
527 {
528 croak "bundle method only available with api => 1 or better" if $_[0]->{api} < 1;
529 require FFI::Platypus::Bundle;
530 goto &_bundle;
531 }
532
533
534 sub package
535 {
536 croak "package method only available with api => 0" if $_[0]->{api} > 0;
537 require FFI::Platypus::Legacy;
538 goto &_package;
539 }
540
541
542 sub abis
543 {
544 require FFI::Platypus::ShareConfig;
545 FFI::Platypus::ShareConfig->get("abi");
546 }
547
548
549 sub abi
550 {
551 my($self, $newabi) = @_;
552 unless($newabi =~ /^[0-9]+$/)
553 {
554 unless(defined $self->abis->{$newabi})
555 {
556 croak "no such ABI: $newabi";
557 }
558 $newabi = $self->abis->{$newabi};
559 }
560
561 unless(FFI::Platypus::ABI::verify($newabi))
562 {
563 croak "no such ABI: $newabi";
564 }
565
566 $self->{abi} = $newabi;
567 $self->{tp}->abi($newabi);
568
569 $self;
570 }
571
572 sub DESTROY
573 {
574 my($self) = @_;
575 foreach my $fini (@{ $self->{fini} })
576 {
577 $fini->($self);
578 }
579 foreach my $handle (values %{ $self->{handles} })
580 {
581 next unless $handle;
582 FFI::Platypus::DL::dlclose($handle);
583 }
584 delete $self->{handles};
585 }
586
587 1;
588
589 __END__
590
591 =pod
592
593 =encoding UTF-8
594
595 =head1 NAME
596
597 FFI::Platypus - Write Perl bindings to non-Perl libraries with FFI. No XS required.
598
599 =head1 VERSION
600
601 version 2.12
602
603 =head1 SYNOPSIS
604
605 use FFI::Platypus 2.00;
606
607 # for all new code you should use api => 2
608 my $ffi = FFI::Platypus->new(
609 api => 2,
610 lib => undef, # search libc
611 );
612
613 # call dynamically
614 $ffi->function( puts => ['string'] => 'int' )->call("hello world");
615
616 # attach as a xsub and call (much faster)
617 $ffi->attach( puts => ['string'] => 'int' );
618 puts("hello world");
619
620 =head1 DESCRIPTION
621
622 Platypus is a library for creating interfaces to machine code libraries
623 written in languages like C, L<C++|FFI::Platypus::Lang::CPP>,
624 L<Go|FFI::Platypus::Lang::Go>,
625 L<Fortran|FFI::Platypus::Lang::Fortran>,
626 L<Rust|FFI::Platypus::Lang::Rust>,
627 L<Pascal|FFI::Platypus::Lang::Pascal>. Essentially anything that gets
628 compiled into machine code. This implementation uses L<libffi|https://sourceware.org/libffi/> to
629 accomplish this task. L<libffi|https://sourceware.org/libffi/> is battle tested by a number of other
630 scripting and virtual machine languages, such as Python and Ruby to
631 serve a similar role. There are a number of reasons why you might want
632 to write an extension with Platypus instead of XS:
633
634 =over 4
635
636 =item FFI / Platypus does not require messing with the guts of Perl
637
638 XS is less of an API and more of the guts of perl splayed out to do
639 whatever you want. That may at times be very powerful, but it can also
640 be a frustrating exercise in hair pulling.
641
642 =item FFI / Platypus is portable
643
644 Lots of languages have FFI interfaces, and it is subjectively easier to
645 port an extension written in FFI in Perl or another language to FFI in
646 another language or Perl. One goal of the Platypus Project is to reduce
647 common interface specifications to a common format like JSON that could
648 be shared between different languages.
649
650 =item FFI / Platypus could be a bridge to Raku
651
652 One of those "other" languages could be Raku and Raku already has an
653 FFI interface I am told.
654
655 =item FFI / Platypus can be reimplemented
656
657 In a bright future with multiple implementations of Perl 5, each
658 interpreter will have its own implementation of Platypus, allowing
659 extensions to be written once and used on multiple platforms, in much
660 the same way that Ruby-FFI extensions can be use in Ruby, JRuby and
661 Rubinius.
662
663 =item FFI / Platypus is pure perl (sorta)
664
665 One Platypus script or module works on any platform where the libraries
666 it uses are available. That means you can deploy your Platypus script
667 in a shared filesystem where they may be run on different platforms. It
668 also means that Platypus modules do not need to be installed in the
669 platform specific Perl library path.
670
671 =item FFI / Platypus is not C or C++ centric
672
673 XS is implemented primarily as a bunch of C macros, which requires at
674 least some understanding of C, the C pre-processor, and some C++ caveats
675 (since on some platforms Perl is compiled and linked with a C++
676 compiler). Platypus on the other hand could be used to call other
677 compiled languages, like L<Fortran|FFI::Platypus::Lang::Fortran>,
678 L<Go|FFI::Platypus::Lang::Go>,
679 L<Rust|FFI::Platypus::Lang::Rust>,
680 L<Pascal|FFI::Platypus::Lang::Pascal>, L<C++|FFI::Platypus::Lang::CPP>,
681 or even L<assembly|FFI::Platypus::Lang::ASM>, allowing you to focus
682 on your strengths.
683
684 =item FFI / Platypus does not require a parser
685
686 L<Inline> isolates the extension developer from XS to some extent, but
687 it also requires a parser. The various L<Inline> language bindings are
688 a great technical achievement, but I think writing a parser for every
689 language that you want to interface with is a bit of an anti-pattern.
690
691 =back
692
693 This document consists of an API reference, a set of examples, some
694 support and development (for contributors) information. If you are new
695 to Platypus or FFI, you may want to skip down to the
696 L<EXAMPLES|/EXAMPLES> to get a taste of what you can do with Platypus.
697
698 Platypus has extensive documentation of types at L<FFI::Platypus::Type>
699 and its custom types API at L<FFI::Platypus::API>.
700
701 You are B<strongly> encouraged to use API level 2 for all new code.
702 There are a number of improvements and design fixes that you get
703 for free. You should even consider updating existing modules to
704 use API level 2 where feasible. How do I do that you might ask?
705 Simply pass in the API level to the platypus constructor.
706
707 my $ffi = FFI::Platypus->new( api => 2 );
708
709 The Platypus documentation has already been updated to assume API
710 level 1.
711
712 =for stopwords ØMQ
713
714 =head1 CONSTRUCTORS
715
716 =head2 new
717
718 my $ffi = FFI::Platypus->new( api => 2, %options);
719
720 Create a new instance of L<FFI::Platypus>.
721
722 Any types defined with this instance will be valid for this instance
723 only, so you do not need to worry about stepping on the toes of other
724 CPAN FFI / Platypus Authors.
725
726 Any functions found will be out of the list of libraries specified with
727 the L<lib|/lib> attribute.
728
729 =head3 options
730
731 =over 4
732
733 =item api
734
735 [version 0.91]
736
737 Sets the API level. The recommended value for all new code is C<2>.
738 The Platypus documentation assumes API level C<2> except for a few
739 places that specifically document older versions. You should
740 only use a lower value for a legacy code base that cannot be migrated to
741 a newer API level. Legal values are:
742
743 =over
744
745 =item C<0>
746
747 Original API level. See L<FFI::Platypus::TypeParser::Version0> for details
748 on the differences.
749
750 =item C<1>
751
752 Enable version 1 API type parser which allows pass-by-value records
753 and type decoration on basic types.
754
755 =item C<2>
756
757 Enable version 2 API.
758 The Platypus documentation assumes this api level is set.
759
760 API version 2 is identical to version 1, except:
761
762 =over 4
763
764 =item Pointer functions that return C<NULL> will return C<undef> instead of empty list
765
766 This fixes a long standing design bug in Platypus.
767
768 =item Array references may be passed to pointer argument types
769
770 This replicates the behavior of array argument types with no size. So the types C<sint8*> and C<sint8[]>
771 behave identically when an array reference is passed in. They differ in that, as before, you can
772 pass a scalar reference into type C<sint8*>.
773
774 =item The fixed string type can be specified without pointer modifier
775
776 That is you can use C<string(10)> instead of C<string(10)*> as you were previously able to
777 in API 0.
778
779 =back
780
781 =back
782
783 =item lib
784
785 Either a pathname (string) or a list of pathnames (array ref of strings)
786 to pre-populate the L<lib|/lib> attribute. Use C<[undef]> to search the
787 current process for symbols.
788
789 0.48
790
791 C<undef> (without the array reference) can be used to search the current
792 process for symbols.
793
794 =item ignore_not_found
795
796 [version 0.15]
797
798 Set the L<ignore_not_found|/ignore_not_found> attribute.
799
800 =item lang
801
802 [version 0.18]
803
804 Set the L<lang|/lang> attribute.
805
806 =back
807
808 =head1 ATTRIBUTES
809
810 =head2 lib
811
812 $ffi->lib($path1, $path2, ...);
813 my @paths = $ffi->lib;
814
815 The list of libraries to search for symbols in.
816
817 The most portable and reliable way to find dynamic libraries is by using
818 L<FFI::CheckLib>, like this:
819
820 use FFI::CheckLib 0.06;
821 $ffi->lib(find_lib_or_die lib => 'archive');
822 # finds libarchive.so on Linux
823 # libarchive.bundle on OS X
824 # libarchive.dll (or archive.dll) on Windows
825 # cygarchive-13.dll on Cygwin
826 # ...
827 # and will die if it isn't found
828
829 L<FFI::CheckLib> has a number of options, such as checking for specific
830 symbols, etc. You should consult the documentation for that module.
831
832 As a special case, if you add C<undef> as a "library" to be searched,
833 Platypus will also search the current process for symbols. This is
834 mostly useful for finding functions in the standard C library, without
835 having to know the name of the standard c library for your platform (as
836 it turns out it is different just about everywhere!).
837
838 You may also use the L</find_lib> method as a shortcut:
839
840 $ffi->find_lib( lib => 'archive' );
841
842 =head2 ignore_not_found
843
844 [version 0.15]
845
846 $ffi->ignore_not_found(1);
847 my $ignore_not_found = $ffi->ignore_not_found;
848
849 Normally the L<attach|/attach> and L<function|/function> methods will
850 throw an exception if it cannot find the name of the function you
851 provide it. This will change the behavior such that
852 L<function|/function> will return C<undef> when the function is not
853 found and L<attach|/attach> will ignore functions that are not found.
854 This is useful when you are writing bindings to a library and have many
855 optional functions and you do not wish to wrap every call to
856 L<function|/function> or L<attach|/attach> in an C<eval>.
857
858 =head2 lang
859
860 [version 0.18]
861
862 $ffi->lang($language);
863
864 Specifies the foreign language that you will be interfacing with. The
865 default is C. The foreign language specified with this attribute
866 changes the default native types (for example, if you specify
867 L<Rust|FFI::Platypus::Lang::Rust>, you will get C<i32> as an alias for
868 C<sint32> instead of C<int> as you do with L<C|FFI::Platypus::Lang::C>).
869
870 If the foreign language plugin supports it, this will also enable
871 Platypus to find symbols using the demangled names (for example, if you
872 specify L<CPP|FFI::Platypus::Lang::CPP> for C++ you can use method names
873 like C<Foo::get_bar()> with L</attach> or L</function>.
874
875 =head2 api
876
877 [version 1.11]
878
879 my $level = $ffi->api;
880
881 Returns the API level of the Platypus instance.
882
883 =head1 METHODS
884
885 =head2 type
886
887 $ffi->type($typename);
888 $ffi->type($typename => $alias);
889
890 Define a type. The first argument is the native or C name of the type.
891 The second argument (optional) is an alias name that you can use to
892 refer to this new type. See L<FFI::Platypus::Type> for legal type
893 definitions.
894
895 Examples:
896
897 $ffi->type('sint32'); # only checks to see that sint32 is a valid type
898 $ffi->type('sint32' => 'myint'); # creates an alias myint for sint32
899 $ffi->type('bogus'); # dies with appropriate diagnostic
900
901 =head2 custom_type
902
903 $ffi->custom_type($alias => {
904 native_type => $native_type,
905 native_to_perl => $coderef,
906 perl_to_native => $coderef,
907 perl_to_native_post => $coderef,
908 });
909
910 Define a custom type. See L<FFI::Platypus::Type#Custom-Types> for details.
911
912 =head2 load_custom_type
913
914 $ffi->load_custom_type($name => $alias, @type_args);
915
916 Load the custom type defined in the module I<$name>, and make an alias
917 I<$alias>. If the custom type requires any arguments, they may be passed
918 in as I<@type_args>. See L<FFI::Platypus::Type#Custom-Types> for
919 details.
920
921 If I<$name> contains C<::> then it will be assumed to be a fully
922 qualified package name. If not, then C<FFI::Platypus::Type::> will be
923 prepended to it.
924
925 =head2 types
926
927 my @types = $ffi->types;
928 my @types = FFI::Platypus->types;
929
930 Returns the list of types that FFI knows about. This will include the
931 native C<libffi> types (example: C<sint32>, C<opaque> and C<double>) and
932 the normal C types (example: C<unsigned int>, C<uint32_t>), any types
933 that you have defined using the L<type|/type> method, and custom types.
934
935 The list of types that Platypus knows about varies somewhat from
936 platform to platform, L<FFI::Platypus::Type> includes a list of the core
937 types that you can always count on having access to.
938
939 It can also be called as a class method, in which case, no user defined
940 or custom types will be included in the list.
941
942 =head2 type_meta
943
944 my $meta = $ffi->type_meta($type_name);
945 my $meta = FFI::Platypus->type_meta($type_name);
946
947 Returns a hash reference with the meta information for the given type.
948
949 It can also be called as a class method, in which case, you won't be
950 able to get meta data on user defined types.
951
952 The format of the meta data is implementation dependent and subject to
953 change. It may be useful for display or debugging.
954
955 Examples:
956
957 my $meta = $ffi->type_meta('int'); # standard int type
958 my $meta = $ffi->type_meta('int[64]'); # array of 64 ints
959 $ffi->type('int[128]' => 'myintarray');
960 my $meta = $ffi->type_meta('myintarray'); # array of 128 ints
961
962 =head2 mangler
963
964 $ffi->mangler(\&mangler);
965
966 Specify a customer mangler to be used for symbol lookup. This is usually useful
967 when you are writing bindings for a library where all of the functions have the
968 same prefix. Example:
969
970 $ffi->mangler(sub {
971 my($symbol) = @_;
972 return "foo_$symbol";
973 });
974
975 $ffi->function( get_bar => [] => 'int' ); # attaches foo_get_bar
976
977 my $f = $ffi->function( set_baz => ['int'] => 'void' );
978 $f->call(22); # calls foo_set_baz
979
980 =head2 function
981
982 my $function = $ffi->function($name => \@argument_types => $return_type);
983 my $function = $ffi->function($address => \@argument_types => $return_type);
984 my $function = $ffi->function($name => \@argument_types => $return_type, \&wrapper);
985 my $function = $ffi->function($address => \@argument_types => $return_type, \&wrapper);
986
987 Returns an object that is similar to a code reference in that it can be
988 called like one.
989
990 Caveat: many situations require a real code reference, so at the price
991 of a performance penalty you can get one like this:
992
993 my $function = $ffi->function(...);
994 my $coderef = sub { $function->(@_) };
995
996 It may be better, and faster to create a real Perl function using the
997 L<attach|/attach> method.
998
999 In addition to looking up a function by name you can provide the address
1000 of the symbol yourself:
1001
1002 my $address = $ffi->find_symbol('my_function');
1003 my $function = $ffi->function($address => ...);
1004
1005 Under the covers, L<function|/function> uses L<find_symbol|/find_symbol>
1006 when you provide it with a name, but it is useful to keep this in mind
1007 as there are alternative ways of obtaining a functions address.
1008 Example: a C function could return the address of another C function
1009 that you might want to call.
1010
1011 [version 0.76]
1012
1013 If the last argument is a code reference, then it will be used as a
1014 wrapper around the function when called. The first argument to the wrapper
1015 will be the inner function, or if it is later attached an xsub. This can be
1016 used if you need to verify/modify input/output data.
1017
1018 Examples:
1019
1020 my $function = $ffi->function('my_function_name', ['int', 'string'] => 'string');
1021 my $return_string = $function->(1, "hi there");
1022
1023 [version 0.91]
1024
1025 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type);
1026 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type, \&wrapper);
1027 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types);
1028 my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => \&wrapper);
1029
1030 Version 0.91 and later allows you to creat functions for c variadic functions
1031 (such as printf, scanf, etc) which can take a variable number of arguments.
1032 The first set of arguments are the fixed set, the second set are the variable
1033 arguments to bind with. The variable argument types must be specified in order
1034 to create a function object, so if you need to call variadic function with
1035 different set of arguments then you will need to create a new function object
1036 each time:
1037
1038 # int printf(const char *fmt, ...);
1039 $ffi->function( printf => ['string'] => ['int'] => 'int' )
1040 ->call("print integer %d\n", 42);
1041 $ffi->function( printf => ['string'] => ['string'] => 'int' )
1042 ->call("print string %s\n", 'platypus');
1043
1044 Some older versions of libffi and possibly some platforms may not support
1045 variadic functions. If you try to create a one, then an exception will be
1046 thrown.
1047
1048 [version 1.26]
1049
1050 If the return type is omitted then C<void> will be the assumed return type.
1051
1052 =head2 attach
1053
1054 $ffi->attach($name => \@argument_types => $return_type);
1055 $ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type);
1056 $ffi->attach([$address => $perl_name] => \@argument_types => $return_type);
1057 $ffi->attach($name => \@argument_types => $return_type, \&wrapper);
1058 $ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type, \&wrapper);
1059 $ffi->attach([$address => $perl_name] => \@argument_types => $return_type, \&wrapper);
1060
1061 Find and attach a C function as a real live Perl xsub. The advantage of
1062 attaching a function over using the L<function|/function> method is that
1063 it is much much much faster since no object resolution needs to be done.
1064 The disadvantage is that it locks the function and the L<FFI::Platypus>
1065 instance into memory permanently, since there is no way to deallocate an
1066 xsub.
1067
1068 If just one I<$name> is given, then the function will be attached in
1069 Perl with the same name as it has in C. The second form allows you to
1070 give the Perl function a different name. You can also provide an
1071 address (the third form), just like with the L<function|/function>
1072 method.
1073
1074 Examples:
1075
1076 $ffi->attach('my_function_name', ['int', 'string'] => 'string');
1077 $ffi->attach(['my_c_function_name' => 'my_perl_function_name'], ['int', 'string'] => 'string');
1078 my $string1 = my_function_name($int);
1079 my $string2 = my_perl_function_name($int);
1080
1081 [version 0.20]
1082
1083 If the last argument is a code reference, then it will be used as a
1084 wrapper around the attached xsub. The first argument to the wrapper
1085 will be the inner xsub. This can be used if you need to verify/modify
1086 input/output data.
1087
1088 Examples:
1089
1090 $ffi->attach('my_function', ['int', 'string'] => 'string', sub {
1091 my($my_function_xsub, $integer, $string) = @_;
1092 $integer++;
1093 $string .= " and another thing";
1094 my $return_string = $my_function_xsub->($integer, $string);
1095 $return_string =~ s/Belgium//; # HHGG remove profanity
1096 $return_string;
1097 });
1098
1099 [version 0.91]
1100
1101 $ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type);
1102 $ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type, \&wrapper);
1103
1104 As of version 0.91 you can attach a variadic functions, if it is supported
1105 by the platform / libffi that you are using. For details see the C<function>
1106 documentation. If not supported by the implementation then an exception
1107 will be thrown.
1108
1109 =head2 closure
1110
1111 my $closure = $ffi->closure($coderef);
1112 my $closure = FFI::Platypus->closure($coderef);
1113
1114 Prepares a code reference so that it can be used as a FFI closure (a
1115 Perl subroutine that can be called from C code). For details on
1116 closures, see L<FFI::Platypus::Type#Closures> and L<FFI::Platypus::Closure>.
1117
1118 =head2 cast
1119
1120 my $converted_value = $ffi->cast($original_type, $converted_type, $original_value);
1121
1122 The C<cast> function converts an existing I<$original_value> of type
1123 I<$original_type> into one of type I<$converted_type>. Not all types
1124 are supported, so care must be taken. For example, to get the address
1125 of a string, you can do this:
1126
1127 my $address = $ffi->cast('string' => 'opaque', $string_value);
1128
1129 Something that won't work is trying to cast an array to anything:
1130
1131 my $address = $ffi->cast('int[10]' => 'opaque', \@list); # WRONG
1132
1133 =head2 attach_cast
1134
1135 $ffi->attach_cast("cast_name", $original_type, $converted_type);
1136 $ffi->attach_cast("cast_name", $original_type, $converted_type, \&wrapper);
1137 my $converted_value = cast_name($original_value);
1138
1139 This function attaches a cast as a permanent xsub. This will make it
1140 faster and may be useful if you are calling a particular cast a lot.
1141
1142 [version 1.26]
1143
1144 A wrapper may be added as the last argument to C<attach_cast> and works
1145 just like the wrapper for C<attach> and C<function> methods.
1146
1147 =head2 sizeof
1148
1149 my $size = $ffi->sizeof($type);
1150 my $size = FFI::Platypus->sizeof($type);
1151
1152 Returns the total size of the given type in bytes. For example to get
1153 the size of an integer:
1154
1155 my $intsize = $ffi->sizeof('int'); # usually 4
1156 my $longsize = $ffi->sizeof('long'); # usually 4 or 8 depending on platform
1157
1158 You can also get the size of arrays
1159
1160 my $intarraysize = $ffi->sizeof('int[64]'); # usually 4*64
1161 my $intarraysize = $ffi->sizeof('long[64]'); # usually 4*64 or 8*64
1162 # depending on platform
1163
1164 Keep in mind that "pointer" types will always be the pointer / word size
1165 for the platform that you are using. This includes strings, opaque and
1166 pointers to other types.
1167
1168 This function is not very fast, so you might want to save this value as
1169 a constant, particularly if you need the size in a loop with many
1170 iterations.
1171
1172 =head2 alignof
1173
1174 [version 0.21]
1175
1176 my $align = $ffi->alignof($type);
1177
1178 Returns the alignment of the given type in bytes.
1179
1180 =head2 kindof
1181
1182 [version 1.24]
1183
1184 my $kind = $ffi->kindof($type);
1185
1186 Returns the kind of a type. This is a string with a value of one of
1187
1188 =over 4
1189
1190 =item C<void>
1191
1192 =item C<scalar>
1193
1194 =item C<string>
1195
1196 =item C<closure>
1197
1198 =item C<record>
1199
1200 =item C<record-value>
1201
1202 =item C<pointer>
1203
1204 =item C<array>
1205
1206 =item C<object>
1207
1208 =back
1209
1210 =head2 countof
1211
1212 [version 1.24]
1213
1214 my $count = $ffi->countof($type);
1215
1216 For array types returns the number of elements in the array (returns 0 for variable length array).
1217 For the C<void> type returns 0. Returns 1 for all other types.
1218
1219 =head2 def
1220
1221 [version 1.24]
1222
1223 $ffi->def($package, $type, $value);
1224 my $value = $ff->def($package, $type);
1225
1226 This method allows you to store data for types. If the C<$package> is not provided, then the
1227 caller's package will be used. C<$type> must be a legal Platypus type for the L<FFI::Platypus>
1228 instance.
1229
1230 =head2 unitof
1231
1232 [version 1.24]
1233
1234 my $unittype = $ffi->unitof($type);
1235
1236 For array and pointer types, returns the basic type without the array or pointer part.
1237 In other words, for C<sin16[]> or C<sint16*> it will return C<sint16>.
1238
1239 =head2 find_lib
1240
1241 [version 0.20]
1242
1243 $ffi->find_lib( lib => $libname );
1244
1245 This is just a shortcut for calling L<FFI::CheckLib#find_lib> and
1246 updating the L</lib> attribute appropriately. Care should be taken
1247 though, as this method simply passes its arguments to
1248 L<FFI::CheckLib#find_lib>, so if your module or script is depending on a
1249 specific feature in L<FFI::CheckLib> then make sure that you update your
1250 prerequisites appropriately.
1251
1252 =head2 find_symbol
1253
1254 my $address = $ffi->find_symbol($name);
1255
1256 Return the address of the given symbol (usually function).
1257
1258 =head2 bundle
1259
1260 [version 0.96 api = 1+]
1261
1262 $ffi->bundle($package, \@args);
1263 $ffi->bundle(\@args);
1264 $ffi->bundle($package);
1265 $ffi->bundle;
1266
1267 This is an interface for bundling compiled code with your
1268 distribution intended to eventually replace the C<package> method documented
1269 above. See L<FFI::Platypus::Bundle> for details on how this works.
1270
1271 =head2 package
1272
1273 [version 0.15 api = 0]
1274
1275 $ffi->package($package, $file); # usually __PACKAGE__ and __FILE__ can be used
1276 $ffi->package; # autodetect
1277
1278 B<Note>: This method is officially discouraged in favor of C<bundle>
1279 described above.
1280
1281 If you use L<FFI::Build> (or the older deprecated L<Module::Build::FFI>
1282 to bundle C code with your distribution, you can use this method to tell
1283 the L<FFI::Platypus> instance to look for symbols that came with the
1284 dynamic library that was built when your distribution was installed.
1285
1286 =head2 abis
1287
1288 my $href = $ffi->abis;
1289 my $href = FFI::Platypus->abis;
1290
1291 Get the legal ABIs supported by your platform and underlying
1292 implementation. What is supported can vary a lot by CPU and by
1293 platform, or even between 32 and 64 bit on the same CPU and platform.
1294 They keys are the "ABI" names, also known as "calling conventions". The
1295 values are integers used internally by the implementation to represent
1296 those ABIs.
1297
1298 =head2 abi
1299
1300 $ffi->abi($name);
1301
1302 Set the ABI or calling convention for use in subsequent calls to
1303 L</function> or L</attach>. May be either a string name or integer
1304 value from the L</abis> method above.
1305
1306 =head1 EXAMPLES
1307
1308 Here are some examples. These examples are provided in full with the
1309 Platypus distribution in the "examples" directory. There are also some
1310 more examples in L<FFI::Platypus::Type> that are related to types.
1311
1312 =head2 Passing and Returning Integers
1313
1314 =head3 C Source
1315
1316 int add(int a, int b) {
1317 return a+b;
1318 }
1319
1320 =head3 Perl Source
1321
1322 use FFI::Platypus 2.00;
1323 use FFI::CheckLib qw( find_lib_or_die );
1324 use File::Basename qw( dirname );
1325
1326 my $ffi = FFI::Platypus->new( api => 2, lib => './add.so' );
1327 $ffi->attach( add => ['int', 'int'] => 'int' );
1328
1329 print add(1,2), "\n"; # prints 3
1330
1331 =head3 Execute
1332
1333 $ cc -shared -o add.so add.c
1334 $ perl add.pl
1335 3
1336
1337 =head3 Discussion
1338
1339 Basic types like integers and floating points are the easiest to pass
1340 across the FFI boundary. Because they are values that are passed on
1341 the stack (or through registers) you don't need to worry about memory
1342 allocations or ownership.
1343
1344 Here we are building our own C dynamic library using the native C
1345 compiler on a Unix like platform. The exact incantation that you
1346 will use to do this would unfortunately depend on your platform and
1347 C compiler.
1348
1349 By default, Platypus uses the
1350 L<Platypus C language plugin|FFI::Platypus::Lang::C>, which gives you
1351 easy access to many of the basic types used by C APIs. (for example
1352 C<int>, C<unsigned long>, C<double>, C<size_t> and others).
1353
1354 If you are working with another language like
1355 L<Fortran|FFI::Platypus::Lang::Fortran/"Passing and Returning Integers">,
1356 L<Go|FFI::Platypus::Lang::Go/"Passing and Returning Integers">,
1357 L<Rust|FFI::Platypus::Lang::Rust/"Passing and Returning Integers"> or
1358 L<Zig|FFI::Platypus::Lang::Zig/"Passing and Returning Integers">,
1359 you will find similar examples where you can use the Platypus language
1360 plugin for that language and use the native types.
1361
1362 =head2 String Arguments (with puts)
1363
1364 =head3 C API
1365
1366 L<cppreference - puts|https://en.cppreference.com/w/c/io/puts>
1367
1368 =head3 Perl Source
1369
1370 use FFI::Platypus 2.00;
1371
1372 my $ffi = FFI::Platypus->new( api => 2, lib => undef );
1373 $ffi->attach( puts => ['string'] => 'int' );
1374
1375 puts("hello world");
1376
1377 =head3 Execute
1378
1379 $ perl puts.pl
1380 hello world
1381
1382 =head3 Discussion
1383
1384 Passing strings into a C function as an argument is also pretty easy
1385 using Platypus. Just use the C<string> type, which is equivalent to
1386 the C <char *> or C<const char *> types.
1387
1388 In this example we are using the C Standard Library's C<puts> function,
1389 so we don't need to build our own C code. We do still need to tell
1390 Platypus where to look for the C<puts> symbol though, which is why
1391 we set C<lib> to C<undef>. This is a special value which tells
1392 Platypus to search the Perl runtime executable itself (including any
1393 dynamic libraries) for symbols. That helpfully includes the C Standard
1394 Library.
1395
1396 =head2 Returning Strings
1397
1398 =head3 C Source
1399
1400 #include <string.h>
1401 #include <stdlib.h>
1402
1403 const char *
1404 string_reverse(const char *input)
1405 {
1406 static char *output = NULL;
1407 int i, len;
1408
1409 if(output != NULL)
1410 free(output);
1411
1412 if(input == NULL)
1413 return NULL;
1414
1415 len = strlen(input);
1416 output = malloc(len+1);
1417
1418 for(i=0; input[i]; i++)
1419 output[len-i-1] = input[i];
1420 output[len] = '\0';
1421
1422 return output;
1423 }
1424
1425 =head3 Perl Source
1426
1427 use FFI::Platypus 2.00;
1428
1429 my $ffi = FFI::Platypus->new(
1430 api => 2,
1431 lib => './string_reverse.so',
1432 );
1433
1434 $ffi->attach( string_reverse => ['string'] => 'string' );
1435
1436 print string_reverse("\nHello world");
1437
1438 string_reverse(undef);
1439
1440 =head3 Execute
1441
1442 $ cc -shared -o string_reverse.so string_reverse.c
1443 $ perl string_reverse.pl
1444 dlrow olleH
1445
1446 =head3 Discussion
1447
1448 The C code here takes an input ASCII string and reverses it, returning
1449 the result. Note that it retains ownership of the string, the caller
1450 is expected to use it before the next call to C<reverse_string>, or
1451 copy it.
1452
1453 The Perl code simply declares the return value as C<string> and is very
1454 simple. This does bring up an inconsistency though, strings passed in
1455 to a function as arguments are passed by reference, whereas the return
1456 value is copied! This is usually what you want because C APIs usually
1457 follow this pattern where you are expected to make your own copy of
1458 the string.
1459
1460 At the end of the program we call C<reverse_string> with C<undef>, which
1461 gets translated to C as C<NULL>. This allows it to free the output buffer
1462 so that the memory will not leak.
1463
1464 =head2 Returning and Freeing Strings with Embedded NULLs
1465
1466 =head3 C Source
1467
1468 #include <string.h>
1469 #include <stdlib.h>
1470
1471 char *
1472 string_crypt(const char *input, int len, const char *key)
1473 {
1474 char *output;
1475 int i, n;
1476
1477 if(input == NULL)
1478 return NULL;
1479
1480 output = malloc(len+1);
1481 output[len] = '\0';
1482
1483 for(i=0, n=0; i<len; i++, n++) {
1484 if(key[n] == '\0')
1485 n = 0;
1486 output[i] = input[i] ^ key[n];
1487 }
1488
1489 return output;
1490 }
1491
1492 void
1493 string_crypt_free(char *output)
1494 {
1495 if(output != NULL)
1496 free(output);
1497 }
1498
1499 =head3 Perl Source
1500
1501 use FFI::Platypus 2.00;
1502 use FFI::Platypus::Buffer qw( buffer_to_scalar );
1503 use YAML ();
1504
1505 my $ffi = FFI::Platypus->new(
1506 api => 2,
1507 lib => './xor_cipher.so',
1508 );
1509
1510 $ffi->attach( string_crypt_free => ['opaque'] );
1511
1512 $ffi->attach( string_crypt => ['string','int','string'] => 'opaque' => sub{
1513 my($xsub, $input, $key) = @_;
1514 my $ptr = $xsub->($input, length($input), $key);
1515 my $output = buffer_to_scalar $ptr, length($input);
1516 string_crypt_free($ptr);
1517 return $output;
1518 });
1519
1520 my $orig = "hello world";
1521 my $key = "foobar";
1522
1523 print YAML::Dump($orig);
1524 my $encrypted = string_crypt($orig, $key);
1525 print YAML::Dump($encrypted);
1526 my $decrypted = string_crypt($encrypted, $key);
1527 print YAML::Dump($decrypted);
1528
1529 =head3 Execute
1530
1531 $ cc -shared -o xor_cipher.so xor_cipher.c
1532 $ perl xor_cipher.pl
1533 --- hello world
1534 --- "\x0e\n\x03\x0e\x0eR\x11\0\x1d\x0e\x05"
1535 --- hello world
1536
1537 =head3 Discussion
1538
1539 The C code here also returns a string, but it has some different expectations,
1540 so we can't just use the C<string> type like we did in the previous example
1541 and copy the string.
1542
1543 This C code implements a simple XOR cipher. Given an input string and a key
1544 it returns an encrypted or decrypted output string where the characters are
1545 XORd with the key. There are some challenges here though. First the input
1546 and output strings can have embedded C<NULL>s in them. For the string passed
1547 in, we can provide the length of the input string. For the output, the
1548 C<string> type expects a C<NULL> terminated string, so we can't use that. So
1549 instead we get a pointer to the output using the C<opaque> type. Because we
1550 know that the output string is the same length as the input string we can
1551 convert the pointer to a regular Perl string using the C<buffer_to_scalar>
1552 function. (For more details about working with buffers and strings see
1553 L<FFI::Platypus::Buffer>).
1554
1555 Next, the C code here does not keep the pointer to the output string, as in
1556 the previous example. We are expected to call C<string_encrypt_free> when
1557 we are done. Since we are getting the pointer back from the C code instead
1558 of copying the string that is easy to do.
1559
1560 Finally, we are using a wrapper to hide a lot of this complexity from our
1561 caller. The last argument to the C<attach> call is a code reference which will
1562 wrap around the C function, which is passed in as the first argument of
1563 the wrapper. This is a good practice when writing modules, to hide the
1564 complexity of C.
1565
1566 =head2 Pointers
1567
1568 =head3 C Source
1569
1570 void
1571 swap(int *a, int *b)
1572 {
1573 int tmp = *b;
1574 *b = *a;
1575 *a = tmp;
1576 }
1577
1578 =head3 Perl Source
1579
1580 use FFI::Platypus 2.00;
1581
1582 my $ffi = FFI::Platypus->new(
1583 api => 2,
1584 lib => './swap.so',
1585 );
1586
1587 $ffi->attach( swap => ['int*','int*'] );
1588
1589 my $a = 1;
1590 my $b = 2;
1591
1592 print "[a,b] = [$a,$b]\n";
1593
1594 swap( \$a, \$b );
1595
1596 print "[a,b] = [$a,$b]\n";
1597
1598 =head3 Execute
1599
1600 $ cc -shared -o swap.so swap.c
1601 $ perl swap.pl
1602 [a,b] = [1,2]
1603 [a,b] = [2,1]
1604
1605 =head3 Discussion
1606
1607 Pointers are often use in C APIs to return simple values like this. Platypus
1608 provides access to pointers to primitive types by appending C<*> to the
1609 primitive type. Here for example we are using C<int*> to create a function
1610 that takes two pointers to integers and swaps their values.
1611
1612 When calling the function from Perl we pass in a reference to a scalar.
1613 Strictly speaking Perl allows modifying the argument values to subroutines, so
1614 we could have allowed just passing in a scalar, but in the design of Platypus
1615 we decided that forcing the use of a reference here emphasizes that you are
1616 passing a reference to the variable, not just the value.
1617
1618 Not pictured in this example, but you can also pass in C<undef> for a pointer
1619 value and that will be translated into C<NULL> on the C side. You can also
1620 return a pointer to a primitive type from a function, again this will be
1621 returned to Perl as a reference to a scalar. Platypus also supports string
1622 pointers (C<string*>). (Though the C equivalent to a C<string*> is a double
1623 pointer to char C<char**>).
1624
1625 =head2 Opaque Pointers (objects)
1626
1627 =head3 C Source
1628
1629 #include <string.h>
1630 #include <stdlib.h>
1631
1632 typedef struct person_t {
1633 char *name;
1634 unsigned int age;
1635 } person_t;
1636
1637 person_t *
1638 person_new(const char *name, unsigned int age) {
1639 person_t *self = malloc(sizeof(person_t));
1640 self->name = strdup(name);
1641 self->age = age;
1642 }
1643
1644 const char *
1645 person_name(person_t *self) {
1646 return self->name;
1647 }
1648
1649 unsigned int
1650 person_age(person_t *self) {
1651 return self->age;
1652 }
1653
1654 void
1655 person_free(person_t *self) {
1656 free(self->name);
1657 free(self);
1658 }
1659
1660 =head3 Perl Source
1661
1662 use FFI::Platypus 2.00;
1663
1664 my $ffi = FFI::Platypus->new(
1665 api => 2,
1666 lib => './person.so',
1667 );
1668
1669 $ffi->type( 'opaque' => 'person_t' );
1670
1671 $ffi->attach( person_new => ['string','unsigned int'] => 'person_t' );
1672 $ffi->attach( person_name => ['person_t'] => 'string' );
1673 $ffi->attach( person_age => ['person_t'] => 'unsigned int' );
1674 $ffi->attach( person_free => ['person_t'] );
1675
1676 my $person = person_new( 'Roger Frooble Bits', 35 );
1677
1678 print "name = ", person_name($person), "\n";
1679 print "age = ", person_age($person), "\n";
1680
1681 person_free($person);
1682
1683 =head3 Execute
1684
1685 $ cc -shared -o person.so person.c
1686 $ perl person.pl
1687 name = Roger Frooble Bits
1688 age = 35
1689
1690 =head3 Discussion
1691
1692 An opaque pointer is a pointer (memory address) that is pointing to I<something>
1693 but you do not know the structure of that something. In C this is usually a
1694 C<void*>, but it could also be a pointer to a C<struct> without a defined body.
1695
1696 This is often used to as an abstraction around objects in C. Here in the C
1697 code we have a C<person_t> struct with functions to create (a constructor), free
1698 (a destructor) and query it (methods).
1699
1700 The Perl code can then use the constructor, methods and destructors without having
1701 to understand the internals. The C<person_t> internals can also be changed
1702 without having to modify the calling code.
1703
1704 We use the Platypus L<type method|/type> to create an alias of C<opaque> called
1705 C<person_t>. While this is not necessary, it does make the Perl code easier
1706 to understand.
1707
1708 In later examples we will see how to hide the use of C<opaque> types further
1709 using the C<object> type, but for some code direct use of C<opaque> is
1710 appropriate.
1711
1712 =head2 Opaque Pointers (buffers and strings)
1713
1714 =head3 C API
1715
1716 =over 4
1717
1718 =item L<cppreference - free|https://en.cppreference.com/w/c/memory/free>
1719
1720 =item L<cppreference - malloc|https://en.cppreference.com/w/c/memory/malloc>
1721
1722 =item L<cppreference - memcpy|https://en.cppreference.com/w/c/string/byte/memcpy>
1723
1724 =item L<cppreference - strdup|https://en.cppreference.com/w/c/string/byte/strdup>
1725
1726 =back
1727
1728 =head3 Perl Source
1729
1730 use FFI::Platypus 2.00;
1731 use FFI::Platypus::Memory qw( malloc free memcpy strdup );
1732
1733 my $ffi = FFI::Platypus->new( api => 2 );
1734 my $buffer = malloc 14;
1735 my $ptr_string = strdup("hello there!!\n");
1736
1737 memcpy $buffer, $ptr_string, 15;
1738
1739 print $ffi->cast('opaque' => 'string', $buffer);
1740
1741 free $ptr_string;
1742 free $buffer;
1743
1744 =head3 Execute
1745
1746 $ perl malloc.pl
1747 hello there!!
1748
1749 =head3 Discussion
1750
1751 Another useful application of the C<opaque> type is for dealing with buffers,
1752 and C strings that you do not immediately need to convert into Perl strings.
1753 This example is completely contrived, but we are using C<malloc> to create a
1754 buffer of 14 bytes. We create a C string using C<strdup>, and then copy it
1755 into the buffer using C<memcpy>. When we are done with the C<opaque> pointers
1756 we can free them using C<free> since they. (This is generally only okay when
1757 freeing memory that was allocated by C<malloc>, which is the case for C<strdup>).
1758
1759 These memory tools, along with others are provided by the L<FFI::Platypus::Memory>
1760 module, which is worth reviewing when you need to manipulate memory from
1761 Perl when writing your FFI code.
1762
1763 Just to verify that the C<memcpy> did the right thing we convert the
1764 buffer into a Perl string and print it out using the Platypus L<cast method|/cast>.
1765
1766 =head2 Arrays
1767
1768 =head3 C Source
1769
1770 void
1771 array_reverse(int a[], int len) {
1772 int tmp, i;
1773
1774 for(i=0; i < len/2; i++) {
1775 tmp = a[i];
1776 a[i] = a[len-i-1];
1777 a[len-i-1] = tmp;
1778 }
1779 }
1780
1781 void
1782 array_reverse10(int a[10]) {
1783 array_reverse(a, 10);
1784 }
1785
1786 =head3 Perl Source
1787
1788 use FFI::Platypus 2.00;
1789
1790 my $ffi = FFI::Platypus->new(
1791 api => 2,
1792 lib => './array_reverse.so',
1793 );
1794
1795 $ffi->attach( array_reverse => ['int[]','int'] );
1796 $ffi->attach( array_reverse10 => ['int[10]'] );
1797
1798 my @a = (1..10);
1799 array_reverse10( \@a );
1800 print "$_ " for @a;
1801 print "\n";
1802
1803 @a = (1..20);
1804 array_reverse( \@a, 20 );
1805 print "$_ " for @a;
1806 print "\n";
1807
1808 =head3 Execute
1809
1810 $ cc -shared -o array_reverse.so array_reverse.c
1811 $ perl array_reverse.pl
1812 10 9 8 7 6 5 4 3 2 1
1813 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
1814
1815 =head3 Discussion
1816
1817 Arrays in C are passed as pointers, so the C code here reverses the array
1818 in place, rather than returning it. Arrays can also be fixed or variable
1819 length. If the array is variable length the length of the array must be
1820 provided in some way. In this case we explicitly pass in a length. Another
1821 way might be to end the array with C<0>, if you don't otherwise expect any
1822 C<0> to appear in your data. For this reason, Platypus adds a zero (or
1823 C<NULL> in the case of pointers) element at the end of the array when passing
1824 it into a variable length array type, although we do not use it here.
1825
1826 With Platypus you can declare an array type as being either fixed or variable
1827 length. Because Perl stores arrays in completely differently than C, a
1828 temporary array is created by Platypus, passed into the C function as a pointer.
1829 When the function returns the array is re-read by Platypus and the Perl array
1830 is updated with the new values. The temporary array is then freed.
1831
1832 You can use any primitive type for arrays, even C<string>. You can also
1833 return an array from a function. As in our discussion about strings, when
1834 you return an array the value is copied, which is usually what you want.
1835
1836 =head2 Pointers as Arrays
1837
1838 =head3 C Source
1839
1840 #include <stdlib.h>
1841
1842 int
1843 array_sum(const int *a) {
1844 int i, sum;
1845 if(a == NULL)
1846 return -1;
1847 for(i=0, sum=0; a[i] != 0; i++)
1848 sum += a[i];
1849 return sum;
1850 }
1851
1852 =head3 Perl Source
1853
1854 use FFI::Platypus 2.00;
1855
1856 my $ffi = FFI::Platypus->new(
1857 api => 2,
1858 lib => './array_sum.so',
1859 );
1860
1861 $ffi->attach( array_sum => ['int*'] => 'int' );
1862
1863 print array_sum(undef), "\n"; # -1
1864 print array_sum([0]), "\n"; # 0
1865 print array_sum([1,2,3,0]), "\n"; # 6
1866
1867 =head3 Execute
1868
1869 $ cc -shared -o array_sum.so array_sum.c
1870 $ perl array_sum.pl
1871 -1
1872 0
1873 6
1874
1875 =head3 Discussion
1876
1877 Starting with the Platypus version 2 API, you can also pass an array reference
1878 in to a pointer argument.
1879
1880 In C pointer and array arguments are often used somewhat interchangeably. In
1881 this example we have an C<array_sum> function that takes a zero terminated
1882 array of integers and computes the sum. If the pointer to the array is zero
1883 (C<0>) then we return C<-1> to indicate an error.
1884
1885 This is the main advantage from Perl for using pointer argument rather than
1886 an array one: the array argument will not let you pass in C<undef> / C<NULL>.
1887
1888 =head2 Sending Strings to GUI on Unix with libnotify
1889
1890 =head3 C API
1891
1892 L<Libnotify Reference Manual|https://developer-old.gnome.org/libnotify/unstable>
1893
1894 =head3 Perl Source
1895
1896 use FFI::CheckLib;
1897 use FFI::Platypus 2.00;
1898
1899 my $ffi = FFI::Platypus->new(
1900 api => 2,
1901 lib => find_lib_or_die(lib => 'notify'),
1902 );
1903
1904 $ffi->attach( notify_init => ['string'] );
1905 $ffi->attach( notify_uninit => [] );
1906 $ffi->attach( notify_notification_new => ['string', 'string', 'string'] => 'opaque' );
1907 $ffi->attach( notify_notification_show => ['opaque', 'opaque'] );
1908
1909 my $message = join "\n",
1910 "Hello from Platypus!",
1911 "Welcome to the fun",
1912 "world of FFI";
1913
1914 notify_init('Platypus Hello');
1915 my $n = notify_notification_new('Platypus Hello World', $message, 'dialog-information');
1916 notify_notification_show($n, undef);
1917 notify_uninit();
1918
1919 =head3 Execute
1920
1921 $ perl notify.pl
1922
1923 =for html <p>And this is what it will look like:</p>
1924 <div style="display: flex">
1925 <div style="margin: 3px; flex: 1 1 50%">
1926 <img alt="Test" src="/examples//notify.png">
1927 </div>
1928 </div>
1929
1930 =head3 Discussion
1931
1932 The GNOME project provides an API to send notifications to its desktop environment.
1933 Nothing here is particularly new: all of the types and techniques are ones that we
1934 have seen before, except we are using a third party library, instead of using our
1935 own C code or the standard C library functions.
1936
1937 When using a third party library you have to know the name or location of it, which
1938 is not typically portable, so here we use L<FFI::CheckLib>'s
1939 L<find_lib_or_die function|FFI::CheckLib/find_lib_or_die>. If the library is not
1940 found the script will die with a useful diagnostic. L<FFI::CheckLib> has a number
1941 of useful features and will integrate nicely with L<Alien::Build> based L<Alien>s.
1942
1943 =head2 The Win32 API with MessageBoxW
1944
1945 =head3 Win32 API
1946
1947 L<MessageBoxW function (winuser.h)|https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw>
1948
1949 =head3 Perl Source
1950
1951 use utf8;
1952 use FFI::Platypus 2.00;
1953
1954 my $ffi = FFI::Platypus->new(
1955 api => 2,
1956 lib => [undef],
1957 );
1958
1959 # see FFI::Platypus::Lang::Win32
1960 $ffi->lang('Win32');
1961
1962 # Send a Unicode string to the Windows API MessageBoxW function.
1963 use constant MB_OK => 0x00000000;
1964 use constant MB_DEFAULT_DESKTOP_ONLY => 0x00020000;
1965 $ffi->attach( [MessageBoxW => 'MessageBox'] => [ 'HWND', 'LPCWSTR', 'LPCWSTR', 'UINT'] => 'int' );
1966 MessageBox(undef, "I ❤️ Platypus", "Confession", MB_OK|MB_DEFAULT_DESKTOP_ONLY);
1967
1968 =head3 Execute
1969
1970 $ perl win32_messagebox.pl
1971
1972 =for html <p>And this is what it will look like:</p>
1973 <div style="display: flex">
1974 <div style="margin: 3px; flex: 1 1 50%">
1975 <img alt="Test" src="/examples/win32_messagebox.png">
1976 </div>
1977 </div>
1978
1979 =head3 Discussion
1980
1981 The API used by Microsoft Windows presents some unique
1982 challenges. On 32 bit systems a different ABI is used than what
1983 is used by the standard C library. It also provides a rats nest of
1984 type aliases. Finally if you want to talk Unicode to any of the
1985 Windows API you will need to use C<UTF-16LE> instead of C<UTF-8>
1986 which is native to Perl. (The Win32 API refers to these as
1987 C<LPWSTR> and C<LPCWSTR> types). As much as possible the Win32
1988 "language" plugin attempts to handle these challenges transparently.
1989 For more details see L<FFI::Platypus::Lang::Win32>.
1990
1991 =head3 Discussion
1992
1993 The libnotify library is a desktop GUI notification system for the
1994 GNOME Desktop environment. This script sends a notification event that
1995 should show up as a balloon, for me it did so in the upper right hand
1996 corner of my screen.
1997
1998 =head2 Structured Data Records (by pointer or by reference)
1999
2000 =head3 C API
2001
2002 L<cppreference - localtime|https://en.cppreference.com/w/c/chrono/localtime>
2003
2004 =head3 Perl Source
2005
2006 use FFI::Platypus 2.00;
2007 use FFI::C;
2008
2009 my $ffi = FFI::Platypus->new(
2010 api => 2,
2011 lib => [undef],
2012 );
2013 FFI::C->ffi($ffi);
2014
2015 package Unix::TimeStruct {
2016
2017 FFI::C->struct(tm => [
2018 tm_sec => 'int',
2019 tm_min => 'int',
2020 tm_hour => 'int',
2021 tm_mday => 'int',
2022 tm_mon => 'int',
2023 tm_year => 'int',
2024 tm_wday => 'int',
2025 tm_yday => 'int',
2026 tm_isdst => 'int',
2027 tm_gmtoff => 'long',
2028 _tm_zone => 'opaque',
2029 ]);
2030
2031 # For now 'string' is unsupported by FFI::C, but we
2032 # can cast the time zone from an opaque pointer to
2033 # string.
2034 sub tm_zone {
2035 my $self = shift;
2036 $ffi->cast('opaque', 'string', $self->_tm_zone);
2037 }
2038
2039 # attach the C localtime function
2040 $ffi->attach( localtime => ['time_t*'] => 'tm', sub {
2041 my($inner, $class, $time) = @_;
2042 $time = time unless defined $time;
2043 $inner->(\$time);
2044 });
2045 }
2046
2047 # now we can actually use our Unix::TimeStruct class
2048 my $time = Unix::TimeStruct->localtime;
2049 printf "time is %d:%d:%d %s\n",
2050 $time->tm_hour,
2051 $time->tm_min,
2052 $time->tm_sec,
2053 $time->tm_zone;
2054
2055 =head3 Execute
2056
2057 $ perl time_struct.pl
2058 time is 3:48:19 MDT
2059
2060 =head3 Discussion
2061
2062 C and other machine code languages frequently provide interfaces that
2063 include structured data records (defined using the C<struct> keyword
2064 in C). Some libraries will provide an API which you are expected to read
2065 or write before and/or after passing them along to the library.
2066
2067 For C pointers to C<strict>, C<union>, nested C<struct> and nested
2068 C<union> structures, the easiest interface to use is via L<FFI::C>.
2069 If you are working with a C<struct> that must be passed by value
2070 (not pointers), then you will want to use L<FFI::Platypus::Record>
2071 class instead. We will discuss an example of that next.
2072
2073 The C C<localtime> function takes a pointer to a C struct. We simply define
2074 the members of the struct using the L<FFI::C> C<struct> method. Because
2075 we used the C<ffi> method to tell L<FFI::C> to use our local instance of
2076 L<FFI::Platypus> it registers the C<tm> type for us, and we can just start
2077 using it as a return type!
2078
2079 =head2 Structured Data Records (on stack or by value)
2080
2081 =head3 C Source
2082
2083 #include <stdint.h>
2084 #include <string.h>
2085
2086 typedef struct color_t {
2087 char name[8];
2088 uint8_t red;
2089 uint8_t green;
2090 uint8_t blue;
2091 } color_t;
2092
2093 color_t
2094 color_increase_red(color_t color, uint8_t amount)
2095 {
2096 strcpy(color.name, "reddish");
2097 color.red += amount;
2098 return color;
2099 }
2100
2101 =head3 Perl Source
2102
2103 use FFI::Platypus 2.00;
2104
2105 my $ffi = FFI::Platypus->new(
2106 api => 2,
2107 lib => './color.so'
2108 );
2109
2110 package Color {
2111
2112 use FFI::Platypus::Record;
2113 use overload
2114 '""' => sub { shift->as_string },
2115 bool => sub { 1 }, fallback => 1;
2116
2117 record_layout_1($ffi,
2118 'string(8)' => 'name', qw(
2119 uint8 red
2120 uint8 green
2121 uint8 blue
2122 ));
2123
2124 sub as_string {
2125 my($self) = @_;
2126 sprintf "%s: [red:%02x green:%02x blue:%02x]",
2127 $self->name, $self->red, $self->green, $self->blue;
2128 }
2129
2130 }
2131
2132 $ffi->type('record(Color)' => 'color_t');
2133 $ffi->attach( color_increase_red => ['color_t','uint8'] => 'color_t' );
2134
2135 my $gray = Color->new(
2136 name => 'gray',
2137 red => 0xDC,
2138 green => 0xDC,
2139 blue => 0xDC,
2140 );
2141
2142 my $slightly_red = color_increase_red($gray, 20);
2143
2144 print "$gray\n";
2145 print "$slightly_red\n";
2146
2147 =head3 Execute
2148
2149 $ cc -shared -o color.so color.c
2150 $ perl color.pl
2151 gray: [red:dc green:dc blue:dc]
2152 reddish: [red:f0 green:dc blue:dc]
2153
2154 =head3 Discussion
2155
2156 In the C source of this example, we pass a C C<struct> by value by
2157 copying it onto the stack. On the Perl side we create a C<Color> class
2158 using L<FFI::Platypus::Record>, which allows us to pass the structure
2159 the way the C source wants us to.
2160
2161 Generally you should only reach for L<FFI::Platypus::Record> if you
2162 need to pass small records on the stack like this. For more complicated
2163 (including nested) data you want to use L<FFI::C> using pointers.
2164
2165 =head2 Avoiding Copy Using Memory Windows (with libzmq3)
2166
2167 =head3 C API
2168
2169 L<ØMQ/3.2.6 API Reference|http://api.zeromq.org/3-2:_start>
2170
2171 =head3 Perl Source
2172
2173 use constant ZMQ_IO_THREADS => 1;
2174 use constant ZMQ_MAX_SOCKETS => 2;
2175 use constant ZMQ_REQ => 3;
2176 use constant ZMQ_REP => 4;
2177 use FFI::CheckLib qw( find_lib_or_die );
2178 use FFI::Platypus 2.00;
2179 use FFI::Platypus::Memory qw( malloc );
2180 use FFI::Platypus::Buffer qw( scalar_to_buffer window );
2181
2182 my $endpoint = "ipc://zmq-ffi-$$";
2183 my $ffi = FFI::Platypus->new(
2184 api => 2,
2185 lib => find_lib_or_die lib => 'zmq',
2186 );
2187
2188 $ffi->attach(zmq_version => ['int*', 'int*', 'int*'] => 'void');
2189
2190 my($major,$minor,$patch);
2191 zmq_version(\$major, \$minor, \$patch);
2192 print "libzmq version $major.$minor.$patch\n";
2193 die "this script only works with libzmq 3 or better" unless $major >= 3;
2194
2195 $ffi->type('opaque' => 'zmq_context');
2196 $ffi->type('opaque' => 'zmq_socket');
2197 $ffi->type('opaque' => 'zmq_msg_t');
2198 $ffi->attach(zmq_ctx_new => [] => 'zmq_context');
2199 $ffi->attach(zmq_ctx_set => ['zmq_context', 'int', 'int'] => 'int');
2200 $ffi->attach(zmq_socket => ['zmq_context', 'int'] => 'zmq_socket');
2201 $ffi->attach(zmq_connect => ['opaque', 'string'] => 'int');
2202 $ffi->attach(zmq_bind => ['zmq_socket', 'string'] => 'int');
2203 $ffi->attach(zmq_send => ['zmq_socket', 'opaque', 'size_t', 'int'] => 'int');
2204 $ffi->attach(zmq_msg_init => ['zmq_msg_t'] => 'int');
2205 $ffi->attach(zmq_msg_recv => ['zmq_msg_t', 'zmq_socket', 'int'] => 'int');
2206 $ffi->attach(zmq_msg_data => ['zmq_msg_t'] => 'opaque');
2207 $ffi->attach(zmq_errno => [] => 'int');
2208 $ffi->attach(zmq_strerror => ['int'] => 'string');
2209
2210 my $context = zmq_ctx_new();
2211 zmq_ctx_set($context, ZMQ_IO_THREADS, 1);
2212
2213 my $socket1 = zmq_socket($context, ZMQ_REQ);
2214 zmq_connect($socket1, $endpoint);
2215
2216 my $socket2 = zmq_socket($context, ZMQ_REP);
2217 zmq_bind($socket2, $endpoint);
2218
2219 { # send
2220 our $sent_message = "hello there";
2221 my($pointer, $size) = scalar_to_buffer $sent_message;
2222 my $r = zmq_send($socket1, $pointer, $size, 0);
2223 die zmq_strerror(zmq_errno()) if $r == -1;
2224 }
2225
2226 { # recv
2227 my $msg_ptr = malloc 100;
2228 zmq_msg_init($msg_ptr);
2229 my $size = zmq_msg_recv($msg_ptr, $socket2, 0);
2230 die zmq_strerror(zmq_errno()) if $size == -1;
2231 my $data_ptr = zmq_msg_data($msg_ptr);
2232 window(my $recv_message, $data_ptr, $size);
2233 print "recv_message = $recv_message\n";
2234 }
2235
2236 =head3 Execute
2237
2238 $ perl zmq3.pl
2239 libzmq version 4.3.4
2240 recv_message = hello there
2241
2242 =head3 Discussion
2243
2244 ØMQ is a high-performance asynchronous messaging library. There are a
2245 few things to note here.
2246
2247 Firstly, sometimes there may be multiple versions of a library in the
2248 wild and you may need to verify that the library on a system meets your
2249 needs (alternatively you could support multiple versions and configure
2250 your bindings dynamically). Here we use C<zmq_version> to ask libzmq
2251 which version it is.
2252
2253 C<zmq_version> returns the version number via three integer pointer
2254 arguments, so we use the pointer to integer type: C<int *>. In order to
2255 pass pointer types, we pass a reference. In this case it is a reference
2256 to an undefined value, because zmq_version will write into the pointers
2257 the output values, but you can also pass in references to integers,
2258 floating point values and opaque pointer types. When the function
2259 returns the C<$major> variable (and the others) has been updated and we
2260 can use it to verify that it supports the API that we require.
2261
2262 Finally we attach the necessary functions, send and receive a message.
2263 When we receive we use the L<FFI::Platypus::Buffer> function C<window>
2264 instead of C<buffer_to_scalar>. They have a similar effect in that
2265 the provide a scalar from a region of memory, but C<window> doesn't
2266 have to copy any data, so it is cheaper to call. The only downside
2267 is that a windowed scalar like this is read-only.
2268
2269 =head2 libarchive
2270
2271 =head3 C Documentation
2272
2273 L<https://www.libarchive.org/>
2274
2275 =head3 Perl Source
2276
2277 use FFI::Platypus 2.00;
2278 use FFI::CheckLib qw( find_lib_or_die );
2279
2280 # This example uses FreeBSD's libarchive to list the contents of any
2281 # archive format that it suppors. We've also filled out a part of
2282 # the ArchiveWrite class that could be used for writing archive formats
2283 # supported by libarchive
2284
2285 my $ffi = FFI::Platypus->new(
2286 api => 2,
2287 lib => find_lib_or_die(lib => 'archive'),
2288 );
2289 $ffi->type('object(Archive)' => 'archive_t');
2290 $ffi->type('object(ArchiveRead)' => 'archive_read_t');
2291 $ffi->type('object(ArchiveWrite)' => 'archive_write_t');
2292 $ffi->type('object(ArchiveEntry)' => 'archive_entry_t');
2293
2294 package Archive {
2295 # base class is "abstract" having no constructor or destructor
2296
2297 $ffi->mangler(sub {
2298 my($name) = @_;
2299 "archive_$name";
2300 });
2301 $ffi->attach( error_string => ['archive_t'] => 'string' );
2302 }
2303
2304 package ArchiveRead {
2305 our @ISA = qw( Archive );
2306
2307 $ffi->mangler(sub {
2308 my($name) = @_;
2309 "archive_read_$name";
2310 });
2311
2312 $ffi->attach( new => ['string'] => 'archive_read_t' );
2313 $ffi->attach( [ free => 'DESTROY' ] => ['archive_t'] );
2314 $ffi->attach( support_filter_all => ['archive_t'] => 'int' );
2315 $ffi->attach( support_format_all => ['archive_t'] => 'int' );
2316 $ffi->attach( open_filename => ['archive_t','string','size_t'] => 'int' );
2317 $ffi->attach( next_header2 => ['archive_t', 'archive_entry_t' ] => 'int' );
2318 $ffi->attach( data_skip => ['archive_t'] => 'int' );
2319 # ... define additional read methods
2320 }
2321
2322 package ArchiveWrite {
2323
2324 our @ISA = qw( Archive );
2325
2326 $ffi->mangler(sub {
2327 my($name) = @_;
2328 "archive_write_$name";
2329 });
2330
2331 $ffi->attach( new => ['string'] => 'archive_write_t' );
2332 $ffi->attach( [ free => 'DESTROY' ] => ['archive_write_t'] );
2333 # ... define additional write methods
2334 }
2335
2336 package ArchiveEntry {
2337
2338 $ffi->mangler(sub {
2339 my($name) = @_;
2340 "archive_entry_$name";
2341 });
2342
2343 $ffi->attach( new => ['string'] => 'archive_entry_t' );
2344 $ffi->attach( [ free => 'DESTROY' ] => ['archive_entry_t'] );
2345 $ffi->attach( pathname => ['archive_entry_t'] => 'string' );
2346 # ... define additional entry methods
2347 }
2348
2349 use constant ARCHIVE_OK => 0;
2350
2351 # this is a Perl version of the C code here:
2352 # https://github.com/libarchive/libarchive/wiki/Examples#List_contents_of_Archive_stored_in_File
2353
2354 my $archive_filename = shift @ARGV;
2355 unless(defined $archive_filename)
2356 {
2357 print "usage: $0 archive.tar\n";
2358 exit;
2359 }
2360
2361 my $archive = ArchiveRead->new;
2362 $archive->support_filter_all;
2363 $archive->support_format_all;
2364
2365 my $r = $archive->open_filename($archive_filename, 1024);
2366 die "error opening $archive_filename: ", $archive->error_string
2367 unless $r == ARCHIVE_OK;
2368
2369 my $entry = ArchiveEntry->new;
2370
2371 while($archive->next_header2($entry) == ARCHIVE_OK)
2372 {
2373 print $entry->pathname, "\n";
2374 $archive->data_skip;
2375 }
2376
2377 =head3 Execute
2378
2379 $ perl archive_object.pl archive.tar
2380 archive.pl
2381 archive_object.pl
2382
2383 =head3 Discussion
2384
2385 libarchive is the implementation of C<tar> for FreeBSD provided as a
2386 library and available on a number of platforms.
2387
2388 One interesting thing about libarchive is that it provides a kind of
2389 object oriented interface via opaque pointers. This example creates an
2390 abstract class C<Archive>, and concrete classes C<ArchiveWrite>,
2391 C<ArchiveRead> and C<ArchiveEntry>. The concrete classes can even be
2392 inherited from and extended just like any Perl classes because of the
2393 way the custom types are implemented. We use Platypus's C<object>
2394 type for this implementation, which is a wrapper around an C<opaque>
2395 (can also be an integer) type that is blessed into a particular class.
2396
2397 Another advanced feature of this example is that we define a mangler
2398 to modify the symbol resolution for each class. This means we can do
2399 this when we define a method for Archive:
2400
2401 $ffi->attach( support_filter_all => ['archive_t'] => 'int' );
2402
2403 Rather than this:
2404
2405 $ffi->attach(
2406 [ archive_read_support_filter_all => 'support_read_filter_all' ] =>
2407 ['archive_t'] => 'int' );
2408 );
2409
2410 As nice as C<libarchive> is, note that we have to shoehorn then
2411 C<archive_free> function name into the Perl convention of using
2412 C<DESTROY> as the destructor. We can easily do that for just this
2413 one function with:
2414
2415 $ffi->attach( [ free => 'DESTROY' ] => ['archive_t'] );
2416
2417 The C<libarchive> is a large library with hundreds of methods.
2418 For comprehensive FFI bindings for C<libarchive> see L<Archive::Libarchive>.
2419
2420 =head2 unix open
2421
2422 =head3 C API
2423
2424 L<Input-output system calls in C|https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-read-write/>
2425
2426 =head3 Perl Source
2427
2428 use FFI::Platypus 2.00;
2429
2430 {
2431 package FD;
2432
2433 use constant O_RDONLY => 0;
2434 use constant O_WRONLY => 1;
2435 use constant O_RDWR => 2;
2436
2437 use constant IN => bless \do { my $in=0 }, __PACKAGE__;
2438 use constant OUT => bless \do { my $out=1 }, __PACKAGE__;
2439 use constant ERR => bless \do { my $err=2 }, __PACKAGE__;
2440
2441 my $ffi = FFI::Platypus->new( api => 2, lib => [undef]);
2442
2443 $ffi->type('object(FD,int)' => 'fd');
2444
2445 $ffi->attach( [ 'open' => 'new' ] => [ 'string', 'int', 'mode_t' ] => 'fd' => sub {
2446 my($xsub, $class, $fn, @rest) = @_;
2447 my $fd = $xsub->($fn, @rest);
2448 die "error opening $fn $!" if $$fd == -1;
2449 $fd;
2450 });
2451
2452 $ffi->attach( write => ['fd', 'string', 'size_t' ] => 'ssize_t' );
2453 $ffi->attach( read => ['fd', 'string', 'size_t' ] => 'ssize_t' );
2454 $ffi->attach( close => ['fd'] => 'int' );
2455 }
2456
2457 my $fd = FD->new("file_handle.txt", FD::O_RDONLY);
2458
2459 my $buffer = "\0" x 10;
2460
2461 while(my $br = $fd->read($buffer, 10))
2462 {
2463 FD::OUT->write($buffer, $br);
2464 }
2465
2466 $fd->close;
2467
2468 =head3 Execute
2469
2470 $ perl file_handle.pl
2471 Hello World
2472
2473 =head3 Discussion
2474
2475 The Unix file system calls use an integer handle for each open file.
2476 We can use the same C<object> type that we used for libarchive above,
2477 except we let platypus know that the underlying type is C<int> instead
2478 of C<opaque> (the latter being the default for the C<object> type).
2479 Mainly just for demonstration since Perl has much better IO libraries,
2480 but now we have an OO interface to the Unix IO functions.
2481
2482 =head2 Varadic Functions (with libcurl)
2483
2484 =head3 C API
2485
2486 =over 4
2487
2488 =item L<curl_easy_init|https://curl.se/libcurl/c/curl_easy_init.html>
2489
2490 =item L<curl_easy_setopt|https://curl.se/libcurl/c/curl_easy_setopt.html>
2491
2492 =item L<curl_easy_perform|https://curl.se/libcurl/c/curl_easy_perform.html>
2493
2494 =item L<curl_easy_cleanup|https://curl.se/libcurl/c/curl_easy_cleanup.html>
2495
2496 =item L<CURLOPT_URL|https://curl.se/libcurl/c/CURLOPT_URL.html>
2497
2498 =back
2499
2500 =head3 Perl Source
2501
2502 use FFI::Platypus 2.00;
2503 use FFI::CheckLib qw( find_lib_or_die );
2504 use constant CURLOPT_URL => 10002;
2505
2506 my $ffi = FFI::Platypus->new(
2507 api => 2,
2508 lib => find_lib_or_die(lib => 'curl'),
2509 );
2510
2511 my $curl_handle = $ffi->function( 'curl_easy_init' => [] => 'opaque' )
2512 ->call;
2513
2514 $ffi->function( 'curl_easy_setopt' => ['opaque', 'enum' ] => ['string'] )
2515 ->call($curl_handle, CURLOPT_URL, "https://pl.atypus.org" );
2516
2517 $ffi->function( 'curl_easy_perform' => ['opaque' ] => 'enum' )
2518 ->call($curl_handle);
2519
2520 $ffi->function( 'curl_easy_cleanup' => ['opaque' ] )
2521 ->call($curl_handle);
2522
2523 =head3 Execute
2524
2525 $ perl curl.pl
2526 <!doctype html>
2527 <html lang="en">
2528 <head>
2529 <meta charset="utf-8" />
2530 <title>pl.atypus.org - Home for the Perl Platypus Project</title>
2531 ...
2532
2533 =head3 Discussion
2534
2535 The L<libcurl|https://curl.se/> library makes extensive use of "varadic" functions.
2536
2537 The C programming language and ABI have the concept of "varadic" functions
2538 that can take a variable number and variable type of arguments. Assuming
2539 you have a C<libffi> that supports it (and most modern systems should),
2540 then you can create bindings to a varadic function by providing two sets
2541 of array references, one for the fixed arguments (for reasons, C varadic
2542 functions must have at least one) and one for variable arguments. In
2543 this example we call C<curl_easy_setopt> as a varadic function.
2544
2545 For functions that have a large or infinite number of possible signatures
2546 it may be impracticable or impossible to attach them all. You can instead
2547 do as we did in this example, create a function object using the
2548 L<function method|/function> and call it immediately. This is not as
2549 performant either when you create or call as using the L<attach method|/attach>,
2550 but in some cases the performance penalty may be worth it or unavoidable.
2551
2552 =head2 Callbacks (with libcurl)
2553
2554 =head3 C API
2555
2556 =over 4
2557
2558 =item L<curl_easy_init|https://curl.se/libcurl/c/curl_easy_init.html>
2559
2560 =item L<curl_easy_setopt|https://curl.se/libcurl/c/curl_easy_setopt.html>
2561
2562 =item L<curl_easy_perform|https://curl.se/libcurl/c/curl_easy_perform.html>
2563
2564 =item L<curl_easy_cleanup|https://curl.se/libcurl/c/curl_easy_cleanup.html>
2565
2566 =item L<CURLOPT_URL|https://curl.se/libcurl/c/CURLOPT_URL.html>
2567
2568 =item L<CURLOPT_WRITEFUNCTION|https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html>
2569
2570 =back
2571
2572 =head3 Perl Source
2573
2574 use FFI::Platypus 2.00;
2575 use FFI::CheckLib qw( find_lib_or_die );
2576 use FFI::Platypus::Buffer qw( window );
2577 use constant CURLOPT_URL => 10002;
2578 use constant CURLOPT_WRITEFUNCTION => 20011;
2579
2580 my $ffi = FFI::Platypus->new(
2581 api => 2,
2582 lib => find_lib_or_die(lib => 'curl'),
2583 );
2584
2585 my $curl_handle = $ffi->function( 'curl_easy_init' => [] => 'opaque' )
2586 ->call;
2587
2588 $ffi->function( 'curl_easy_setopt' => [ 'opaque', 'enum' ] => ['string'] )
2589 ->call($curl_handle, CURLOPT_URL, "https://pl.atypus.org" );
2590
2591 my $html;
2592
2593 my $closure = $ffi->closure(sub {
2594 my($ptr, $len, $num, $user) = @_;
2595 window(my $buf, $ptr, $len*$num);
2596 $html .= $buf;
2597 return $len*$num;
2598 });
2599
2600 $ffi->function( 'curl_easy_setopt' => [ 'opaque', 'enum' ] => ['(opaque,size_t,size_t,opaque)->size_t'] => 'enum' )
2601 ->call($curl_handle, CURLOPT_WRITEFUNCTION, $closure);
2602
2603 $ffi->function( 'curl_easy_perform' => [ 'opaque' ] => 'enum' )
2604 ->call($curl_handle);
2605
2606 $ffi->function( 'curl_easy_cleanup' => [ 'opaque' ] )
2607 ->call($curl_handle);
2608
2609 if($html =~ /<title>(.*?)<\/title>/) {
2610 print "$1\n";
2611 }
2612
2613 =head3 Execute
2614
2615 $ perl curl_callback.pl
2616 pl.atypus.org - Home for the Perl Platypus Project
2617
2618 =head3 Discussion
2619
2620 This example is similar to the previous one, except instead of letting
2621 L<libcurl|https://curl.se> write the content body to C<STDOUT>, we give
2622 it a callback to send the data to instead. The L<closure method|/closure>
2623 can be used to create a callback function pointer that can be called from
2624 C. The type for the callback is in the form C<< (arg_type,arg_type,etc)->return_type >>
2625 where the argument types are in parentheticals with an arrow between the
2626 argument types and the return type.
2627
2628 Inside the closure or callback we use the L<window function|FFI::Platypus::Buffer/window>
2629 from L<FFI::Platypus::Buffer> again to avoid an I<extra> copy. We still
2630 have to copy the buffer to append it to C<$hmtl> but it is at least one
2631 less copy.
2632
2633 =head2 bundle your own code
2634
2635 =head3 C Source
2636
2637 C<ffi/foo.c>:
2638
2639 #include <ffi_platypus_bundle.h>
2640 #include <string.h>
2641
2642 typedef struct {
2643 char *name;
2644 int value;
2645 } foo_t;
2646
2647 foo_t*
2648 foo__new(const char *class_name, const char *name, int value) {
2649 (void)class_name;
2650 foo_t *self = malloc( sizeof( foo_t ) );
2651 self->name = strdup(name);
2652 self->value = value;
2653 return self;
2654 }
2655
2656 const char *
2657 foo__name(foo_t *self) {
2658 return self->name;
2659 }
2660
2661 int
2662 foo__value(foo_t *self) {
2663 return self->value;
2664 }
2665
2666 void
2667 foo__DESTROY(foo_t *self) {
2668 free(self->name);
2669 free(self);
2670 }
2671
2672 =head3 Perl Source
2673
2674 C<lib/Foo.pm>:
2675
2676 package Foo;
2677
2678 use strict;
2679 use warnings;
2680 use FFI::Platypus 2.00;
2681
2682 my $ffi = FFI::Platypus->new( api => 2 );
2683
2684 $ffi->type('object(Foo)' => 'foo_t');
2685 $ffi->mangler(sub {
2686 my $name = shift;
2687 $name =~ s/^/foo__/;
2688 $name;
2689 });
2690
2691 $ffi->bundle;
2692
2693 $ffi->attach( new => [ 'string', 'string', 'int' ] => 'foo_t' );
2694 $ffi->attach( name => [ 'foo_t' ] => 'string' );
2695 $ffi->attach( value => [ 'foo_t' ] => 'int' );
2696 $ffi->attach( DESTROY => [ 'foo_t' ] => 'void' );
2697
2698 1;
2699
2700 C<t/foo.t>:
2701
2702 use Test2::V0;
2703 use Foo;
2704
2705 my $foo = Foo->new("platypus", 10);
2706 isa_ok $foo, 'Foo';
2707 is $foo->name, "platypus";
2708 is $foo->value, 10;
2709
2710 done_testing;
2711
2712 C<Makefile.PL>:
2713
2714 use ExtUtils::MakeMaker;
2715 use FFI::Build::MM;
2716 my $fbmm = FFI::Build::MM->new;
2717 WriteMakefile(
2718 $fbmm->mm_args(
2719 NAME => 'Foo',
2720 DISTNAME => 'Foo',
2721 VERSION => '1.00',
2722 # ...
2723 )
2724 );
2725
2726 sub MY::postamble
2727 {
2728 $fbmm->mm_postamble;
2729 }
2730
2731 =head3 Execute
2732
2733 With prove:
2734
2735 $ prove -lvm
2736 t/foo.t ..
2737 # Seeded srand with seed '20221105' from local date.
2738 ok 1 - Foo=SCALAR->isa('Foo')
2739 ok 2
2740 ok 3
2741 1..3
2742 ok
2743 All tests successful.
2744 Files=1, Tests=3, 0 wallclock secs ( 0.00 usr 0.00 sys + 0.10 cusr 0.00 csys = 0.10 CPU)
2745 Result: PASS
2746
2747 With L<ExtUtils::MakeMaker>:
2748
2749 $ perl Makefile.PL
2750 Generating a Unix-style Makefile
2751 Writing Makefile for Foo
2752 Writing MYMETA.yml and MYMETA.json
2753 $ make
2754 cp lib/Foo.pm blib/lib/Foo.pm
2755 "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" -MFFI::Build::MM=cmd -e fbx_build
2756 CC ffi/foo.c
2757 LD blib/lib/auto/share/dist/Foo/lib/libFoo.so
2758 $ make test
2759 "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" -MFFI::Build::MM=cmd -e fbx_build
2760 "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" -MFFI::Build::MM=cmd -e fbx_test
2761 PERL_DL_NONLAZY=1 "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test::Harness::Switches; test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
2762 t/foo.t .. ok
2763 All tests successful.
2764 Files=1, Tests=3, 1 wallclock secs ( 0.00 usr 0.00 sys + 0.03 cusr 0.00 csys = 0.03 CPU)
2765 Result: PASS
2766
2767 =head3 Discussion
2768
2769 You can bundle your own C code with your Perl extension. There are a number
2770 of reasons you might want to do this Sometimes you need to optimize a
2771 tight loop for speed. Or you might need a little bit of glue code for your
2772 bindings to a library that isn't inherently FFI friendly. Either way
2773 what you want is the L<FFI::Build> system on the install step and the
2774 L<FFI::Platypus::Bundle> interface on the runtime step. If you are using
2775 L<Dist::Zilla> for your distribution, you will also want to check out the
2776 L<Dist::Zilla::Plugin::FFI::Build> plugin to make this as painless as possible.
2777
2778 One of the nice things about the bundle interface is that it is smart enough to
2779 work with either L<App::Prove> or L<ExtUtils::MakeMaker>. This means, unlike
2780 XS, you do not need to explicitly compile your C code in development mode, that
2781 will be done for you when you call C<< $ffi->bundle >>
2782
2783 =head1 FAQ
2784
2785 =head2 How do I get constants defined as macros in C header files
2786
2787 This turns out to be a challenge for any language calling into C, which
2788 frequently uses C<#define> macros to define constants like so:
2789
2790 #define FOO_STATIC 1
2791 #define FOO_DYNAMIC 2
2792 #define FOO_OTHER 3
2793
2794 As macros are expanded and their definitions are thrown away by the C pre-processor
2795 there isn't any way to get the name/value mappings from the compiled dynamic
2796 library.
2797
2798 You can manually create equivalent constants in your Perl source:
2799
2800 use constant FOO_STATIC => 1;
2801 use constant FOO_DYNAMIC => 2;
2802 use constant FOO_OTHER => 3;
2803
2804 If there are a lot of these types of constants you might want to consider using
2805 a tool (L<Convert::Binary::C> can do this) that can extract the constants for you.
2806
2807 See also the "Integer constants" example in L<FFI::Platypus::Type>.
2808
2809 You can also use the new Platypus bundle interface to define Perl constants
2810 from C space. This is more reliable, but does require a compiler at install
2811 time. It is recommended mainly for writing bindings against libraries that
2812 have constants that can vary widely from platform to platform. See
2813 L<FFI::Platypus::Constant> for details.
2814
2815 =head2 What about enums?
2816
2817 The C enum types are integers. The underlying type is up to the platform, so
2818 Platypus provides C<enum> and C<senum> types for unsigned and singed enums
2819 respectively. At least some compilers treat signed and unsigned enums as
2820 different types. The enum I<values> are essentially the same as macro constants
2821 described above from an FFI perspective. Thus the process of defining enum values
2822 is identical to the process of defining macro constants in Perl.
2823
2824 For more details on enumerated types see L<FFI::Platypus::Type/"Enum types">.
2825
2826 There is also a type plugin (L<FFI::Platypus::Type::Enum>) that can be helpful
2827 in writing interfaces that use enums.
2828
2829 =head2 Memory leaks
2830
2831 There are a couple places where memory is allocated, but never deallocated that may
2832 look like memory leaks by tools designed to find memory leaks like valgrind. This
2833 memory is intended to be used for the lifetime of the perl process so there normally
2834 this isn't a problem unless you are embedding a Perl interpreter which doesn't closely
2835 match the lifetime of your overall application.
2836
2837 Specifically:
2838
2839 =over 4
2840
2841 =item type cache
2842
2843 some types are cached and not freed. These are needed as long as there are FFI
2844 functions that could be called.
2845
2846 =item attached functions
2847
2848 Attaching a function as an xsub will definitely allocate memory that won't be freed
2849 because the xsub could be called at any time, including in C<END> blocks.
2850
2851 =back
2852
2853 The Platypus team plans on adding a hook to free some of this "leaked" memory
2854 for use cases where Perl and Platypus are embedded in a larger application
2855 where the lifetime of the Perl process is significantly smaller than the
2856 overall lifetime of the whole process.
2857
2858 =head2 I get seg faults on some platforms but not others with a library using pthreads.
2859
2860 On some platforms, Perl isn't linked with C<libpthreads> if Perl threads are not
2861 enabled. On some platforms this doesn't seem to matter, C<libpthreads> can be
2862 loaded at runtime without much ill-effect. (Linux from my experience doesn't seem
2863 to mind one way or the other). Some platforms are not happy about this, and about
2864 the only thing that you can do about it is to build Perl such that it links with
2865 C<libpthreads> even if it isn't a threaded Perl.
2866
2867 This is not really an FFI issue, but a Perl issue, as you will have the same
2868 problem writing XS code for the such libraries.
2869
2870 =head2 Doesn't work on Perl 5.10.0.
2871
2872 The first point release of Perl 5.10 was buggy, and is not supported by Platypus.
2873 Please upgrade to a newer Perl.
2874
2875 =head1 CAVEATS
2876
2877 Platypus and Native Interfaces like libffi rely on the availability of
2878 dynamic libraries. Things not supported include:
2879
2880 =over 4
2881
2882 =item Systems that lack dynamic library support
2883
2884 Like MS-DOS
2885
2886 =item Systems that are not supported by libffi
2887
2888 Like OpenVMS
2889
2890 =item Languages that do not support using dynamic libraries from other languages
2891
2892 This used to be the case with Google's Go, but is no longer the case. This is
2893 a problem for C / XS code as well.
2894
2895 =item Languages that do not compile to machine code
2896
2897 Like .NET based languages and Java.
2898
2899 =back
2900
2901 The documentation has a bias toward using FFI / Platypus with C. This
2902 is my fault, as my background mainly in C/C++ programmer (when I am
2903 not writing Perl). In many places I use "C" as a short form for "any
2904 language that can generate machine code and is callable from C". I
2905 welcome pull requests to the Platypus core to address this issue. In an
2906 attempt to ease usage of Platypus by non C programmers, I have written a
2907 number of foreign language plugins for various popular languages (see
2908 the SEE ALSO below). These plugins come with examples specific to those
2909 languages, and documentation on common issues related to using those
2910 languages with FFI. In most cases these are available for easy adoption
2911 for those with the know-how or the willingness to learn. If your
2912 language doesn't have a plugin YET, that is just because you haven't
2913 written it yet.
2914
2915 =head1 SUPPORT
2916
2917 The intent of the C<FFI-Platypus> team is to support the same versions of
2918 Perl that are supported by the Perl toolchain. As of this writing that
2919 means 5.16 and better.
2920
2921 IRC: #native on irc.perl.org
2922
2923 L<(click for instant chat room login)|http://chat.mibbit.com/#[email protected]>
2924
2925 If something does not work the way you think it should, or if you have a
2926 feature request, please open an issue on this project's GitHub Issue
2927 tracker:
2928
2929 L<https://github.com/perlFFI/FFI-Platypus/issues>
2930
2931 =head1 SECURITY
2932
2933 If you have identified a security vulnerability in the code, or the
2934 possibility of one, please report it right away using GitHub's private
2935 vulnerability reporting feature at
2936 L<https://github.com/PerlFFI/FFI-Platypus/security/advisories/new>,
2937 rather than this project's public GitHub issue tracker, so that a fix
2938 can be prepared before any public disclosure.
2939
2940 The maintainer will try to respond promptly, and will release a fix
2941 as soon as reasonably possible. Please keep in mind, though, that
2942 C<FFI-Platypus> is maintained by volunteers in their spare time, and a
2943 rapid response cannot be guaranteed.
2944
2945 Security fixes will normally only be made for the most recent
2946 production release.
2947
2948 You may also report the issue to L<CPANSec|https://security.metacpan.org/>,
2949 particularly if the issue is urgent or you do not get a response from
2950 the maintainer in a reasonable amount of time.
2951
2952 =head1 CONTRIBUTING
2953
2954 If you have implemented a new feature or fixed a bug then you may make a
2955 pull request on this project's GitHub repository:
2956
2957 L<https://github.com/PerlFFI/FFI-Platypus/pulls>
2958
2959 This project is developed using L<Dist::Zilla>. The project's git
2960 repository also comes with the C<Makefile.PL> file necessary
2961 for building, testing (and even installing if necessary) without
2962 L<Dist::Zilla>. Please keep in mind though that these files are
2963 generated so if changes need to be made to those files they should be
2964 done through the project's C<dist.ini> file. If you do use
2965 L<Dist::Zilla> and already have the necessary plugins installed, then I
2966 encourage you to run C<dzil test> before making any pull requests. This
2967 is not a requirement, however, I am happy to integrate especially
2968 smaller patches that need tweaking to fit the project standards. I may
2969 push back and ask you to write a test case or alter the formatting of a
2970 patch depending on the amount of time I have and the amount of code that
2971 your patch touches.
2972
2973 This project's GitHub issue tracker listed above is not Write-Only. If
2974 you want to contribute then feel free to browse through the existing
2975 issues and see if there is something you feel you might be good at and
2976 take a whack at the problem. I frequently open issues myself that I
2977 hope will be accomplished by someone in the future but do not have time
2978 to immediately implement myself.
2979
2980 Another good area to help out in is documentation. I try to make sure
2981 that there is good document coverage, that is there should be
2982 documentation describing all the public features and warnings about
2983 common pitfalls, but an outsider's or alternate view point on such
2984 things would be welcome; if you see something confusing or lacks
2985 sufficient detail I encourage documentation only pull requests to
2986 improve things.
2987
2988 The Platypus distribution comes with a test library named C<libtest>
2989 that is normally automatically built by C<./Build test>. If you prefer
2990 to use C<prove> or run tests directly, you can use the C<./Build
2991 libtest> command to build it. Example:
2992
2993 % perl Makefile.PL
2994 % make
2995 % make ffi-test
2996 % prove -bv t
2997 # or an individual test
2998 % perl -Mblib t/ffi_platypus_memory.t
2999
3000 The build process also respects these environment variables:
3001
3002 =over 4
3003
3004 =item FFI_PLATYPUS_DEBUG_FAKE32
3005
3006 When building Platypus on 32 bit Perls, it will use the L<Math::Int64> C
3007 API and make L<Math::Int64> a prerequisite. Setting this environment
3008 variable will force Platypus to build with both of those options on a 64
3009 bit Perl as well.
3010
3011 % env FFI_PLATYPUS_DEBUG_FAKE32=1 perl Makefile.PL
3012 DEBUG_FAKE32:
3013 + making Math::Int64 a prereq
3014 + Using Math::Int64's C API to manipulate 64 bit values
3015 Generating a Unix-style Makefile
3016 Writing Makefile for FFI::Platypus
3017 Writing MYMETA.yml and MYMETA.json
3018 %
3019
3020 =item FFI_PLATYPUS_NO_ALLOCA
3021
3022 Platypus uses the non-standard and somewhat controversial C function
3023 C<alloca> by default on platforms that support it. I believe that
3024 Platypus uses it responsibly to allocate small amounts of memory for
3025 argument type parameters, and does not use it to allocate large
3026 structures like arrays or buffers. If you prefer not to use C<alloca>
3027 despite these precautions, then you can turn its use off by setting this
3028 environment variable when you run C<Makefile.PL>:
3029
3030 helix% env FFI_PLATYPUS_NO_ALLOCA=1 perl Makefile.PL
3031 NO_ALLOCA:
3032 + alloca() will not be used, even if your platform supports it.
3033 Generating a Unix-style Makefile
3034 Writing Makefile for FFI::Platypus
3035 Writing MYMETA.yml and MYMETA.json
3036
3037 =item V
3038
3039 When building platypus may hide some of the excessive output when
3040 probing and building, unless you set C<V> to a true value.
3041
3042 % env V=1 perl Makefile.PL
3043 % make V=1
3044 ...
3045
3046 =back
3047
3048 =head2 Coding Guidelines
3049
3050 =over 4
3051
3052 =item
3053
3054 Do not hesitate to make code contribution. Making useful contributions
3055 is more important than following byzantine bureaucratic coding
3056 regulations. We can always tweak things later.
3057
3058 =item
3059
3060 Please make an effort to follow existing coding style when making pull
3061 requests.
3062
3063 =item
3064
3065 The intent of the C<FFI-Platypus> team is to support the same versions of
3066 Perl that are supported by the Perl toolchain. As of this writing that
3067 means 5.16 and better. As such, please do not include any code that
3068 requires a newer version of Perl.
3069
3070 =back
3071
3072 =head2 Performance Testing
3073
3074 As Mark Twain was fond of saying there are four types of lies: lies,
3075 damn lies, statistics and benchmarks. That being said, it can sometimes
3076 be helpful to compare the runtime performance of Platypus if you are
3077 making significant changes to the Platypus Core. For that I use
3078 `FFI-Performance`, which can be found in my GitHub repository here:
3079
3080 =over 4
3081
3082 =item L<https://github.com/Perl5-FFI/FFI-Performance>
3083
3084 =back
3085
3086 =head2 System integrators
3087
3088 This distribution uses L<Alien::FFI> in fallback mode, meaning if
3089 the system doesn't provide C<pkg-config> and C<libffi> it will attempt
3090 to download C<libffi> and build it from source. If you are including
3091 Platypus in a larger system (for example a Linux distribution) you
3092 only need to make sure to declare C<pkg-config> or C<pkgconf> and
3093 the development package for C<libffi> as prereqs for this module.
3094
3095 =head1 SEE ALSO
3096
3097 =head2 Extending Platypus
3098
3099 =over 4
3100
3101 =item L<FFI::Platypus::Type>
3102
3103 Type definitions for Platypus.
3104
3105 =item L<FFI::C>
3106
3107 Interface for defining structured data records for use with
3108 Platypus. It supports C C<struct>, C<union>, nested structures
3109 and arrays of all of those. It only supports passing these
3110 types by reference or pointer, so if you need to pass structured
3111 data by value see L<FFI::Platypus::Record> below.
3112
3113 =item L<FFI::Platypus::Record>
3114
3115 Interface for defining structured data records for use with
3116 Platypus. Included in the Platypus core. Supports pass by
3117 value which is uncommon in C, but frequently used in languages
3118 like Rust and Go. Consider using L<FFI::C> instead if you
3119 don't need to pass by value.
3120
3121 =item L<FFI::Platypus::API>
3122
3123 The custom types API for Platypus.
3124
3125 =item L<FFI::Platypus::Memory>
3126
3127 Memory functions for FFI.
3128
3129 =back
3130
3131 =head2 Languages
3132
3133 =over 4
3134
3135 =item L<FFI::Platypus::Lang::C>
3136
3137 Documentation and tools for using Platypus with the C programming
3138 language
3139
3140 =item L<FFI::Platypus::Lang::CPP>
3141
3142 Documentation and tools for using Platypus with the C++ programming
3143 language
3144
3145 =item L<FFI::Platypus::Lang::Fortran>
3146
3147 Documentation and tools for using Platypus with Fortran
3148
3149 =item L<FFI::Platypus::Lang::Go>
3150
3151 Documentation and tools for using Platypus with Go
3152
3153 =item L<FFI::Platypus::Lang::Pascal>
3154
3155 Documentation and tools for using Platypus with Free Pascal
3156
3157 =item L<FFI::Platypus::Lang::Rust>
3158
3159 Documentation and tools for using Platypus with the Rust programming
3160 language
3161
3162 =item L<FFI::Platypus::Lang::ASM>
3163
3164 Documentation and tools for using Platypus with the Assembly
3165
3166 =item L<FFI::Platypus::Lang::Win32>
3167
3168 Documentation and tools for using Platypus with the Win32 API.
3169
3170 =item L<FFI::Platypus::Lang::Zig>
3171
3172 Documentation and tools for using Platypus with the Zig programming
3173 language
3174
3175 =item L<Wasm> and L<Wasm::Wasmtime>
3176
3177 Modules for writing WebAssembly bindings in Perl. This allows you to call
3178 functions written in any language supported by WebAssembly. These modules
3179 are also implemented using Platypus.
3180
3181 =back
3182
3183 =head2 Other Tools Related Tools Useful for FFI
3184
3185 =over 4
3186
3187 =item L<FFI::CheckLib>
3188
3189 Find dynamic libraries in a portable way.
3190
3191 =item L<Convert::Binary::C>
3192
3193 A great interface for decoding C data structures, including C<struct>s,
3194 C<enum>s, C<#define>s and more.
3195
3196 =item L<pack and unpack|perlpacktut>
3197
3198 Native to Perl functions that can be used to decode C C<struct> types.
3199
3200 =item L<C::Scan>
3201
3202 This module can extract constants and other useful objects from C header
3203 files that may be relevant to an FFI application. One downside is that
3204 its use may require development packages to be installed.
3205
3206 =back
3207
3208 =head2 Other Foreign Function Interfaces
3209
3210 =over 4
3211
3212 =item L<Affix>
3213
3214 A wrapper around L<infix|https://github.com/sanko/infix>, an FFI-focused
3215 just-in-time (JIT) compiler.
3216
3217 =item L<NativeCall>
3218
3219 Promising interface to Platypus inspired by Raku.
3220
3221 =item L<Win32::API>
3222
3223 Microsoft Windows specific FFI style interface.
3224
3225 =item L<FFI>
3226
3227 Older, simpler, less featureful FFI. It used to be implemented
3228 using FSF's C<ffcall>. Because C<ffcall> has been unsupported for
3229 some time, I reimplemented this module using L<FFI::Platypus>.
3230
3231 =item L<C::DynaLib>
3232
3233 Another FFI for Perl that doesn't appear to have worked for a long time.
3234
3235 =item L<C::Blocks>
3236
3237 Embed a tiny C compiler into your Perl scripts.
3238
3239 =item L<P5NCI>
3240
3241 Yet another FFI like interface that does not appear to be supported or
3242 under development anymore.
3243
3244 =back
3245
3246 =head2 Other
3247
3248 =over 4
3249
3250 =item L<Alien::FFI>
3251
3252 Provides libffi for Platypus during its configuration and build stages.
3253
3254 =back
3255
3256 =head1 ACKNOWLEDGMENTS
3257
3258 In addition to the contributors mentioned below, I would like to
3259 acknowledge Brock Wilcox (AWWAIID) and Meredith Howard (MHOWARD) whose
3260 work on C<FFI::Sweet> not only helped me get started with FFI but
3261 significantly influenced the design of Platypus.
3262
3263 Dan Book, who goes by Grinnz on IRC for answering user questions about
3264 FFI and Platypus.
3265
3266 In addition I'd like to thank Alessandro Ghedini (ALEXBIO) whose work
3267 on another Perl FFI library helped drive some of the development ideas
3268 for L<FFI::Platypus>.
3269
3270 =head1 AUTHOR
3271
3272 Author: Graham Ollis E<lt>[email protected]<gt>
3273
3274 Contributors:
3275
3276 Bakkiaraj Murugesan (bakkiaraj)
3277
3278 Dylan Cali (calid)
3279
3280 pipcet
3281
3282 Zaki Mughal (zmughal)
3283
3284 Fitz Elliott (felliott)
3285
3286 Vickenty Fesunov (vyf)
3287
3288 Gregor Herrmann (gregoa)
3289
3290 Shlomi Fish (shlomif)
3291
3292 Damyan Ivanov
3293
3294 Ilya Pavlov (Ilya33)
3295
3296 Petr Písař (ppisar)
3297
3298 Mohammad S Anwar (MANWAR)
3299
3300 Håkon Hægland (hakonhagland, HAKONH)
3301
3302 Meredith (merrilymeredith, MHOWARD)
3303
3304 Diab Jerius (DJERIUS)
3305
3306 Eric Brine (IKEGAMI)
3307
3308 szTheory
3309
3310 José Joaquín Atria (JJATRIA)
3311
3312 Pete Houston (openstrike, HOUSTON)
3313
3314 Lukas Mai (MAUKE)
3315
3316 =head1 COPYRIGHT AND LICENSE
3317
3318 This software is copyright (c) 2015-2022 by Graham Ollis.
3319
3320 This is free software; you can redistribute it and/or modify it under
3321 the same terms as the Perl 5 programming language system itself.
3322
3323 =cut