1FFI::Platypus(3)      User Contributed Perl Documentation     FFI::Platypus(3)
2
3
4

NAME

6       FFI::Platypus - Write Perl bindings to non-Perl libraries with FFI. No
7       XS required.
8

VERSION

10       version 1.43
11

SYNOPSIS

13        use FFI::Platypus 1.00;
14
15        # for all new code you should use api => 1
16        my $ffi = FFI::Platypus->new( api => 1 );
17        $ffi->lib(undef); # search libc
18
19        # call dynamically
20        $ffi->function( puts => ['string'] => 'int' )->call("hello world");
21
22        # attach as a xsub and call (much faster)
23        $ffi->attach( puts => ['string'] => 'int' );
24        puts("hello world");
25

DESCRIPTION

27       Platypus is a library for creating interfaces to machine code libraries
28       written in languages like C, C++, Go, Fortran, Rust, Pascal.
29       Essentially anything that gets compiled into machine code.  This
30       implementation uses "libffi" to accomplish this task.  "libffi" is
31       battle tested by a number of other scripting and virtual machine
32       languages, such as Python and Ruby to serve a similar role.  There are
33       a number of reasons why you might want to write an extension with
34       Platypus instead of XS:
35
36       FFI / Platypus does not require messing with the guts of Perl
37           XS is less of an API and more of the guts of perl splayed out to do
38           whatever you want.  That may at times be very powerful, but it can
39           also be a frustrating exercise in hair pulling.
40
41       FFI / Platypus is portable
42           Lots of languages have FFI interfaces, and it is subjectively
43           easier to port an extension written in FFI in Perl or another
44           language to FFI in another language or Perl.  One goal of the
45           Platypus Project is to reduce common interface specifications to a
46           common format like JSON that could be shared between different
47           languages.
48
49       FFI / Platypus could be a bridge to Perl 6
50           One of those "other" languages could be Perl 6 and Perl 6 already
51           has an FFI interface I am told.
52
53       FFI / Platypus can be reimplemented
54           In a bright future with multiple implementations of Perl 5, each
55           interpreter will have its own implementation of Platypus, allowing
56           extensions to be written once and used on multiple platforms, in
57           much the same way that Ruby-FFI extensions can be use in Ruby,
58           JRuby and Rubinius.
59
60       FFI / Platypus is pure perl (sorta)
61           One Platypus script or module works on any platform where the
62           libraries it uses are available.  That means you can deploy your
63           Platypus script in a shared filesystem where they may be run on
64           different platforms.  It also means that Platypus modules do not
65           need to be installed in the platform specific Perl library path.
66
67       FFI / Platypus is not C or C++ centric
68           XS is implemented primarily as a bunch of C macros, which requires
69           at least some understanding of C, the C pre-processor, and some C++
70           caveats (since on some platforms Perl is compiled and linked with a
71           C++ compiler). Platypus on the other hand could be used to call
72           other compiled languages, like Fortran, Go, Rust, Pascal, C++, or
73           even assembly, allowing you to focus on your strengths.
74
75       FFI / Platypus does not require a parser
76           Inline isolates the extension developer from XS to some extent, but
77           it also requires a parser.  The various Inline language bindings
78           are a great technical achievement, but I think writing a parser for
79           every language that you want to interface with is a bit of an anti-
80           pattern.
81
82       This document consists of an API reference, a set of examples, some
83       support and development (for contributors) information.  If you are new
84       to Platypus or FFI, you may want to skip down to the EXAMPLES to get a
85       taste of what you can do with Platypus.
86
87       Platypus has extensive documentation of types at FFI::Platypus::Type
88       and its custom types API at FFI::Platypus::API.
89
90       You are strongly encouraged to use API level 1 for all new code.  There
91       are a number of improvements and design fixes that you get for free.
92       You should even consider updating existing modules to use API level 1
93       where feasible.  How do I do that you might ask?  Simply pass in the
94       API level to the platypus constructor.
95
96        my $ffi = FFI::Platypus->new( api => 1 );
97
98       The Platypus documentation has already been updated to assume API level
99       1.
100

CONSTRUCTORS

102   new
103        my $ffi = FFI::Platypus->new( api => 1, %options);
104
105       Create a new instance of FFI::Platypus.
106
107       Any types defined with this instance will be valid for this instance
108       only, so you do not need to worry about stepping on the toes of other
109       CPAN FFI / Platypus Authors.
110
111       Any functions found will be out of the list of libraries specified with
112       the lib attribute.
113
114       options
115
116       api Sets the API level.  Legal values are
117
118           0   Original API level.  See FFI::Platypus::TypeParser::Version0
119               for details on the differences.
120
121           1   Enable the next generation type parser which allows pass-by-
122               value records and type decoration on basic types.  Using API
123               level 1 prior to Platypus version 1.00 will trigger a (noisy)
124               warning.
125
126               All new code should be written with this set to 1!  The
127               Platypus documentation assumes this api level is set.
128
129       lib Either a pathname (string) or a list of pathnames (array ref of
130           strings) to pre-populate the lib attribute.  Use "[undef]" to
131           search the current process for symbols.
132
133           0.48
134
135           "undef" (without the array reference) can be used to search the
136           current process for symbols.
137
138       ignore_not_found
139           [version 0.15]
140
141           Set the ignore_not_found attribute.
142
143       lang
144           [version 0.18]
145
146           Set the lang attribute.
147

ATTRIBUTES

149   lib
150        $ffi->lib($path1, $path2, ...);
151        my @paths = $ffi->lib;
152
153       The list of libraries to search for symbols in.
154
155       The most portable and reliable way to find dynamic libraries is by
156       using FFI::CheckLib, like this:
157
158        use FFI::CheckLib 0.06;
159        $ffi->lib(find_lib_or_die lib => 'archive');
160          # finds libarchive.so on Linux
161          #       libarchive.bundle on OS X
162          #       libarchive.dll (or archive.dll) on Windows
163          #       cygarchive-13.dll on Cygwin
164          #       ...
165          # and will die if it isn't found
166
167       FFI::CheckLib has a number of options, such as checking for specific
168       symbols, etc.  You should consult the documentation for that module.
169
170       As a special case, if you add "undef" as a "library" to be searched,
171       Platypus will also search the current process for symbols. This is
172       mostly useful for finding functions in the standard C library, without
173       having to know the name of the standard c library for your platform (as
174       it turns out it is different just about everywhere!).
175
176       You may also use the "find_lib" method as a shortcut:
177
178        $ffi->find_lib( lib => 'archive' );
179
180   ignore_not_found
181       [version 0.15]
182
183        $ffi->ignore_not_found(1);
184        my $ignore_not_found = $ffi->ignore_not_found;
185
186       Normally the attach and function methods will throw an exception if it
187       cannot find the name of the function you provide it.  This will change
188       the behavior such that function will return "undef" when the function
189       is not found and attach will ignore functions that are not found.  This
190       is useful when you are writing bindings to a library and have many
191       optional functions and you do not wish to wrap every call to function
192       or attach in an "eval".
193
194   lang
195       [version 0.18]
196
197        $ffi->lang($language);
198
199       Specifies the foreign language that you will be interfacing with. The
200       default is C.  The foreign language specified with this attribute
201       changes the default native types (for example, if you specify Rust, you
202       will get "i32" as an alias for "sint32" instead of "int" as you do with
203       C).
204
205       If the foreign language plugin supports it, this will also enable
206       Platypus to find symbols using the demangled names (for example, if you
207       specify CPP for C++ you can use method names like "Foo::get_bar()" with
208       "attach" or "function".
209
210   api
211       [version 1.11]
212
213        my $level = $ffi->api;
214
215       Returns the API level of the Platypus instance.
216

METHODS

218   type
219        $ffi->type($typename);
220        $ffi->type($typename => $alias);
221
222       Define a type.  The first argument is the native or C name of the type.
223       The second argument (optional) is an alias name that you can use to
224       refer to this new type.  See FFI::Platypus::Type for legal type
225       definitions.
226
227       Examples:
228
229        $ffi->type('sint32');            # only checks to see that sint32 is a valid type
230        $ffi->type('sint32' => 'myint'); # creates an alias myint for sint32
231        $ffi->type('bogus');             # dies with appropriate diagnostic
232
233   custom_type
234        $ffi->custom_type($alias => {
235          native_type         => $native_type,
236          native_to_perl      => $coderef,
237          perl_to_native      => $coderef,
238          perl_to_native_post => $coderef,
239        });
240
241       Define a custom type.  See FFI::Platypus::Type#Custom-Types for
242       details.
243
244   load_custom_type
245        $ffi->load_custom_type($name => $alias, @type_args);
246
247       Load the custom type defined in the module $name, and make an alias
248       $alias. If the custom type requires any arguments, they may be passed
249       in as @type_args. See FFI::Platypus::Type#Custom-Types for details.
250
251       If $name contains "::" then it will be assumed to be a fully qualified
252       package name. If not, then "FFI::Platypus::Type::" will be prepended to
253       it.
254
255   types
256        my @types = $ffi->types;
257        my @types = FFI::Platypus->types;
258
259       Returns the list of types that FFI knows about.  This will include the
260       native "libffi" types (example: "sint32", "opaque" and "double") and
261       the normal C types (example: "unsigned int", "uint32_t"), any types
262       that you have defined using the type method, and custom types.
263
264       The list of types that Platypus knows about varies somewhat from
265       platform to platform, FFI::Platypus::Type includes a list of the core
266       types that you can always count on having access to.
267
268       It can also be called as a class method, in which case, no user defined
269       or custom types will be included in the list.
270
271   type_meta
272        my $meta = $ffi->type_meta($type_name);
273        my $meta = FFI::Platypus->type_meta($type_name);
274
275       Returns a hash reference with the meta information for the given type.
276
277       It can also be called as a class method, in which case, you won't be
278       able to get meta data on user defined types.
279
280       The format of the meta data is implementation dependent and subject to
281       change.  It may be useful for display or debugging.
282
283       Examples:
284
285        my $meta = $ffi->type_meta('int');        # standard int type
286        my $meta = $ffi->type_meta('int[64]');    # array of 64 ints
287        $ffi->type('int[128]' => 'myintarray');
288        my $meta = $ffi->type_meta('myintarray'); # array of 128 ints
289
290   mangler
291        $ffi->mangler(\&mangler);
292
293       Specify a customer mangler to be used for symbol lookup.  This is
294       usually useful when you are writing bindings for a library where all of
295       the functions have the same prefix.  Example:
296
297        $ffi->mangler(sub {
298          my($symbol) = @_;
299          return "foo_$symbol";
300        });
301
302        $ffi->function( get_bar => [] => 'int' );  # attaches foo_get_bar
303
304        my $f = $ffi->function( set_baz => ['int'] => 'void' );
305        $f->call(22); # calls foo_set_baz
306
307   function
308        my $function = $ffi->function($name => \@argument_types => $return_type);
309        my $function = $ffi->function($address => \@argument_types => $return_type);
310        my $function = $ffi->function($name => \@argument_types => $return_type, \&wrapper);
311        my $function = $ffi->function($address => \@argument_types => $return_type, \&wrapper);
312
313       Returns an object that is similar to a code reference in that it can be
314       called like one.
315
316       Caveat: many situations require a real code reference, so at the price
317       of a performance penalty you can get one like this:
318
319        my $function = $ffi->function(...);
320        my $coderef = sub { $function->(@_) };
321
322       It may be better, and faster to create a real Perl function using the
323       attach method.
324
325       In addition to looking up a function by name you can provide the
326       address of the symbol yourself:
327
328        my $address = $ffi->find_symbol('my_function');
329        my $function = $ffi->function($address => ...);
330
331       Under the covers, function uses find_symbol when you provide it with a
332       name, but it is useful to keep this in mind as there are alternative
333       ways of obtaining a functions address.  Example: a C function could
334       return the address of another C function that you might want to call,
335       or modules such as FFI::TinyCC produce machine code at runtime that you
336       can call from Platypus.
337
338       [version 0.76]
339
340       If the last argument is a code reference, then it will be used as a
341       wrapper around the function when called.  The first argument to the
342       wrapper will be the inner function, or if it is later attached an xsub.
343       This can be used if you need to verify/modify input/output data.
344
345       Examples:
346
347        my $function = $ffi->function('my_function_name', ['int', 'string'] => 'string');
348        my $return_string = $function->(1, "hi there");
349
350       [version 0.91]
351
352        my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type);
353        my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type, \&wrapper);
354        my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types);
355        my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => \&wrapper);
356
357       Version 0.91 and later allows you to creat functions for c variadic
358       functions (such as printf, scanf, etc) which can take a variable number
359       of arguments.  The first set of arguments are the fixed set, the second
360       set are the variable arguments to bind with.  The variable argument
361       types must be specified in order to create a function object, so if you
362       need to call variadic function with different set of arguments then you
363       will need to create a new function object each time:
364
365        # int printf(const char *fmt, ...);
366        $ffi->function( printf => ['string'] => ['int'] => 'int' )
367            ->call("print integer %d\n", 42);
368        $ffi->function( printf => ['string'] => ['string'] => 'int' )
369            ->call("print string %s\n", 'platypus');
370
371       Some older versions of libffi and possibly some platforms may not
372       support variadic functions.  If you try to create a one, then an
373       exception will be thrown.
374
375       [version 1.26]
376
377       If the return type is omitted then "void" will be the assumed return
378       type.
379
380   attach
381        $ffi->attach($name => \@argument_types => $return_type);
382        $ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type);
383        $ffi->attach([$address => $perl_name] => \@argument_types => $return_type);
384        $ffi->attach($name => \@argument_types => $return_type, \&wrapper);
385        $ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type, \&wrapper);
386        $ffi->attach([$address => $perl_name] => \@argument_types => $return_type, \&wrapper);
387
388       Find and attach a C function as a real live Perl xsub.  The advantage
389       of attaching a function over using the function method is that it is
390       much much much faster since no object resolution needs to be done.  The
391       disadvantage is that it locks the function and the FFI::Platypus
392       instance into memory permanently, since there is no way to deallocate
393       an xsub.
394
395       If just one $name is given, then the function will be attached in Perl
396       with the same name as it has in C.  The second form allows you to give
397       the Perl function a different name.  You can also provide an address
398       (the third form), just like with the function method.
399
400       Examples:
401
402        $ffi->attach('my_function_name', ['int', 'string'] => 'string');
403        $ffi->attach(['my_c_function_name' => 'my_perl_function_name'], ['int', 'string'] => 'string');
404        my $string1 = my_function_name($int);
405        my $string2 = my_perl_function_name($int);
406
407       [version 0.20]
408
409       If the last argument is a code reference, then it will be used as a
410       wrapper around the attached xsub.  The first argument to the wrapper
411       will be the inner xsub.  This can be used if you need to verify/modify
412       input/output data.
413
414       Examples:
415
416        $ffi->attach('my_function', ['int', 'string'] => 'string', sub {
417          my($my_function_xsub, $integer, $string) = @_;
418          $integer++;
419          $string .= " and another thing";
420          my $return_string = $my_function_xsub->($integer, $string);
421          $return_string =~ s/Belgium//; # HHGG remove profanity
422          $return_string;
423        });
424
425       [version 0.91]
426
427        $ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type);
428        $ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type, \&wrapper);
429
430       As of version 0.91 you can attach a variadic functions, if it is
431       supported by the platform / libffi that you are using.  For details see
432       the "function" documentation.  If not supported by the implementation
433       then an exception will be thrown.
434
435   closure
436        my $closure = $ffi->closure($coderef);
437        my $closure = FFI::Platypus->closure($coderef);
438
439       Prepares a code reference so that it can be used as a FFI closure (a
440       Perl subroutine that can be called from C code).  For details on
441       closures, see FFI::Platypus::Type#Closures and FFI::Platypus::Closure.
442
443   cast
444        my $converted_value = $ffi->cast($original_type, $converted_type, $original_value);
445
446       The "cast" function converts an existing $original_value of type
447       $original_type into one of type $converted_type.  Not all types are
448       supported, so care must be taken.  For example, to get the address of a
449       string, you can do this:
450
451        my $address = $ffi->cast('string' => 'opaque', $string_value);
452
453       Something that won't work is trying to cast an array to anything:
454
455        my $address = $ffi->cast('int[10]' => 'opaque', \@list);  # WRONG
456
457   attach_cast
458        $ffi->attach_cast("cast_name", $original_type, $converted_type);
459        $ffi->attach_cast("cast_name", $original_type, $converted_type, \&wrapper);
460        my $converted_value = cast_name($original_value);
461
462       This function attaches a cast as a permanent xsub.  This will make it
463       faster and may be useful if you are calling a particular cast a lot.
464
465       [version 1.26]
466
467       A wrapper may be added as the last argument to "attach_cast" and works
468       just like the wrapper for "attach" and "function" methods.
469
470   sizeof
471        my $size = $ffi->sizeof($type);
472        my $size = FFI::Platypus->sizeof($type);
473
474       Returns the total size of the given type in bytes.  For example to get
475       the size of an integer:
476
477        my $intsize = $ffi->sizeof('int');   # usually 4
478        my $longsize = $ffi->sizeof('long'); # usually 4 or 8 depending on platform
479
480       You can also get the size of arrays
481
482        my $intarraysize = $ffi->sizeof('int[64]');  # usually 4*64
483        my $intarraysize = $ffi->sizeof('long[64]'); # usually 4*64 or 8*64
484                                                     # depending on platform
485
486       Keep in mind that "pointer" types will always be the pointer / word
487       size for the platform that you are using.  This includes strings,
488       opaque and pointers to other types.
489
490       This function is not very fast, so you might want to save this value as
491       a constant, particularly if you need the size in a loop with many
492       iterations.
493
494   alignof
495       [version 0.21]
496
497        my $align = $ffi->alignof($type);
498
499       Returns the alignment of the given type in bytes.
500
501   kindof
502       [version 1.24]
503
504        my $kind = $ffi->kindof($type);
505
506       Returns the kind of a type.  This is a string with a value of one of
507
508       "void"
509       "scalar"
510       "string"
511       "closure"
512       "record"
513       "record-value"
514       "pointer"
515       "array"
516       "object"
517
518   countof
519       [version 1.24]
520
521        my $count = $ffi->countof($type);
522
523       For array types returns the number of elements in the array (returns 0
524       for variable length array).  For the "void" type returns 0.  Returns 1
525       for all other types.
526
527   def
528       [version 1.24]
529
530        $ffi->def($package, $type, $value);
531        my $value = $ff->def($package, $type);
532
533       This method allows you to store data for types.  If the $package is not
534       provided, then the caller's package will be used.  $type must be a
535       legal Platypus type for the FFI::Platypus instance.
536
537   unitof
538       [version 1.24]
539
540        my $unittype = $ffi->unitof($type);
541
542       For array and pointer types, returns the basic type without the array
543       or pointer part.  In other words, for "sin16[]" or "sint16*" it will
544       return "sint16".
545
546   find_lib
547       [version 0.20]
548
549        $ffi->find_lib( lib => $libname );
550
551       This is just a shortcut for calling FFI::CheckLib#find_lib and updating
552       the "lib" attribute appropriately.  Care should be taken though, as
553       this method simply passes its arguments to FFI::CheckLib#find_lib, so
554       if your module or script is depending on a specific feature in
555       FFI::CheckLib then make sure that you update your prerequisites
556       appropriately.
557
558   find_symbol
559        my $address = $ffi->find_symbol($name);
560
561       Return the address of the given symbol (usually function).
562
563   bundle
564       [version 0.96 api = 1+]
565
566        $ffi->bundle($package, \@args);
567        $ffi->bundle(\@args);
568        $ffi->bundle($package);
569        $ffi->bundle;
570
571       This is an interface for bundling compiled code with your distribution
572       intended to eventually replace the "package" method documented above.
573       See FFI::Platypus::Bundle for details on how this works.
574
575   package
576       [version 0.15 api = 0]
577
578        $ffi->package($package, $file); # usually __PACKAGE__ and __FILE__ can be used
579        $ffi->package;                  # autodetect
580
581       Note: This method is officially discouraged in favor of "bundle"
582       described above.
583
584       If you use FFI::Build (or the older deprecated Module::Build::FFI to
585       bundle C code with your distribution, you can use this method to tell
586       the FFI::Platypus instance to look for symbols that came with the
587       dynamic library that was built when your distribution was installed.
588
589   abis
590        my $href = $ffi->abis;
591        my $href = FFI::Platypus->abis;
592
593       Get the legal ABIs supported by your platform and underlying
594       implementation.  What is supported can vary a lot by CPU and by
595       platform, or even between 32 and 64 bit on the same CPU and platform.
596       They keys are the "ABI" names, also known as "calling conventions".
597       The values are integers used internally by the implementation to
598       represent those ABIs.
599
600   abi
601        $ffi->abi($name);
602
603       Set the ABI or calling convention for use in subsequent calls to
604       "function" or "attach".  May be either a string name or integer value
605       from the "abis" method above.
606

EXAMPLES

608       Here are some examples.  These examples are provided in full with the
609       Platypus distribution in the "examples" directory.  There are also some
610       more examples in FFI::Platypus::Type that are related to types.
611
612   Integer conversions
613        use FFI::Platypus 1.00;
614
615        my $ffi = FFI::Platypus->new( api => 1 );
616        $ffi->lib(undef);
617
618        $ffi->attach(puts => ['string'] => 'int');
619        $ffi->attach(atoi => ['string'] => 'int');
620
621        puts(atoi('56'));
622
623       Discussion: "puts" and "atoi" should be part of the standard C library
624       on all platforms.  "puts" prints a string to standard output, and
625       "atoi" converts a string to integer.  Specifying "undef" as a library
626       tells Platypus to search the current process for symbols, which
627       includes the standard c library.
628
629   libnotify
630        use FFI::CheckLib;
631        use FFI::Platypus 1.00;
632
633        # NOTE: I ported this from anoter Perl FFI library and it seems to work most
634        # of the time, but also seems to SIGSEGV sometimes.  I saw the same behavior
635        # in the old version, and am not really familiar with the libnotify API to
636        # say what is the cause.  Patches welcome to fix it.
637
638        my $ffi = FFI::Platypus->new( api => 1 );
639        $ffi->lib(find_lib_or_exit lib => 'notify');
640
641        $ffi->attach(notify_init   => ['string'] => 'void');
642        $ffi->attach(notify_uninit => []       => 'void');
643        $ffi->attach([notify_notification_new    => 'notify_new']    => ['string', 'string', 'string']           => 'opaque');
644        $ffi->attach([notify_notification_update => 'notify_update'] => ['opaque', 'string', 'string', 'string'] => 'void');
645        $ffi->attach([notify_notification_show   => 'notify_show']   => ['opaque', 'opaque']                     => 'void');
646
647        notify_init('FFI::Platypus');
648        my $n = notify_new('','','');
649        notify_update($n, 'FFI::Platypus', 'It works!!!', 'media-playback-start');
650        notify_show($n, undef);
651        notify_uninit();
652
653       Discussion: libnotify is a desktop GUI notification library for the
654       GNOME Desktop environment. This script sends a notification event that
655       should show up as a balloon, for me it did so in the upper right hand
656       corner of my screen.
657
658       The most portable way to find the correct name and location of a
659       dynamic library is via the FFI::CheckLib#find_lib family of functions.
660       If you are putting together a CPAN distribution, you should also
661       consider using FFI::CheckLib#check_lib_or_exit function in your
662       "Build.PL" or "Makefile.PL" file (If you are using Dist::Zilla, check
663       out the Dist::Zilla::Plugin::FFI::CheckLib plugin). This will provide a
664       user friendly diagnostic letting the user know that the required
665       library is missing, and reduce the number of bogus CPAN testers results
666       that you will get.
667
668       Also in this example, we rename some of the functions when they are
669       placed into Perl space to save typing:
670
671        $ffi->attach( [notify_notification_new => 'notify_new']
672          => ['string','string','string']
673          => 'opaque'
674        );
675
676       When you specify a list reference as the "name" of the function the
677       first element is the symbol name as understood by the dynamic library.
678       The second element is the name as it will be placed in Perl space.
679
680       Later, when we call "notify_new":
681
682        my $n = notify_new('','','');
683
684       We are really calling the C function "notify_notification_new".
685
686   Allocating and freeing memory
687        use FFI::Platypus 1.00;
688        use FFI::Platypus::Memory qw( malloc free memcpy );
689
690        my $ffi = FFI::Platypus->new( api => 1 );
691        my $buffer = malloc 12;
692
693        memcpy $buffer, $ffi->cast('string' => 'opaque', "hello there"), length "hello there\0";
694
695        print $ffi->cast('opaque' => 'string', $buffer), "\n";
696
697        free $buffer;
698
699       Discussion: "malloc" and "free" are standard memory allocation
700       functions available from the standard c library and.  Interfaces to
701       these and other memory related functions are provided by the
702       FFI::Platypus::Memory module.
703
704   structured data records
705        use FFI::Platypus 1.00;
706        use FFI::C;
707
708        my $ffi = FFI::Platypus->new(
709          api => 1,
710          lib => [undef],
711        );
712        FFI::C->ffi($ffi);
713
714        package Unix::TimeStruct {
715
716          FFI::C->struct(tm => [
717            tm_sec    => 'int',
718            tm_min    => 'int',
719            tm_hour   => 'int',
720            tm_mday   => 'int',
721            tm_mon    => 'int',
722            tm_year   => 'int',
723            tm_wday   => 'int',
724            tm_yday   => 'int',
725            tm_isdst  => 'int',
726            tm_gmtoff => 'long',
727            _tm_zone  => 'opaque',
728          ]);
729
730          # For now 'string' is unsupported by FFI::C, but we
731          # can cast the time zone from an opaque pointer to
732          # string.
733          sub tm_zone {
734            my $self = shift;
735            $ffi->cast('opaque', 'string', $self->_tm_zone);
736          }
737
738          # attach the C localtime function
739          $ffi->attach( localtime => ['time_t*'] => 'tm', sub {
740            my($inner, $class, $time) = @_;
741            $time = time unless defined $time;
742            $inner->(\$time);
743          });
744        }
745
746        # now we can actually use our My::UnixTime class
747        my $time = Unix::TimeStruct->localtime;
748        printf "time is %d:%d:%d %s\n",
749          $time->tm_hour,
750          $time->tm_min,
751          $time->tm_sec,
752          $time->tm_zone;
753
754       Discussion: C and other machine code languages frequently provide
755       interfaces that include structured data records (known as "structs" in
756       C).  They sometimes provide an API in which you are expected to
757       manipulate these records before and/or after passing them along to C
758       functions.  For C pointers to structs, unions and arrays of structs and
759       unions, the easiest interface to use is via FFI::C.  If you are working
760       with structs that must be passed as values (not pointers), then you
761       want to use the FFI::Platypus::Record class instead.  We will discuss
762       this class later.
763
764       The C "localtime" function takes a pointer to a C struct.  We simply
765       define the members of the struct using the FFI::C "struct" method.
766       Because we used the "ffi" method to tell FFI::C to use our local
767       instance of FFI::Platypus it registers the "tm" type for us, and we can
768       just start using it as a return type!
769
770   structured data records by-value
771   libuuid
772        use FFI::CheckLib;
773        use FFI::Platypus 1.00;
774        use FFI::Platypus::Memory qw( malloc free );
775
776        my $ffi = FFI::Platypus->new( api => 1 );
777        $ffi->lib(find_lib_or_exit lib => 'uuid');
778        $ffi->type('string(37)*' => 'uuid_string');
779        $ffi->type('record(16)*' => 'uuid_t');
780
781        $ffi->attach(uuid_generate => ['uuid_t'] => 'void');
782        $ffi->attach(uuid_unparse  => ['uuid_t','uuid_string'] => 'void');
783
784        my $uuid = "\0" x $ffi->sizeof('uuid_t');
785        uuid_generate($uuid);
786
787        my $string = "\0" x $ffi->sizeof('uuid_string');
788        uuid_unparse($uuid, $string);
789
790        print "$string\n";
791
792       Discussion: libuuid is a library used to generate unique identifiers
793       (UUID) for objects that may be accessible beyond the local system.  The
794       library is or was part of the Linux e2fsprogs package.
795
796       Knowing the size of objects is sometimes important.  In this example,
797       we use the sizeof function to get the size of 16 characters (in this
798       case it is simply 16 bytes).  We also know that the strings "deparsed"
799       by "uuid_unparse" are exactly 37 bytes.
800
801   puts and getpid
802        use FFI::Platypus 1.00;
803
804        my $ffi = FFI::Platypus->new( api => 1 );
805        $ffi->lib(undef);
806
807        $ffi->attach(puts => ['string'] => 'int');
808        $ffi->attach(getpid => [] => 'int');
809
810        puts(getpid());
811
812       Discussion: "puts" is part of standard C library on all platforms.
813       "getpid" is available on Unix type platforms.
814
815   Math library
816        use FFI::Platypus 1.00;
817        use FFI::CheckLib;
818
819        my $ffi = FFI::Platypus->new( api => 1 );
820        $ffi->lib(undef);
821        $ffi->attach(puts => ['string'] => 'int');
822        $ffi->attach(fdim => ['double','double'] => 'double');
823
824        puts(fdim(7.0, 2.0));
825
826        $ffi->attach(cos => ['double'] => 'double');
827
828        puts(cos(2.0));
829
830        $ffi->attach(fmax => ['double', 'double'] => 'double');
831
832        puts(fmax(2.0,3.0));
833
834       Discussion: On UNIX the standard c library math functions are
835       frequently provided in a separate library "libm", so you could search
836       for those symbols in "libm.so", but that won't work on non-UNIX
837       platforms like Microsoft Windows.  Fortunately Perl uses the math
838       library so these symbols are already in the current process so you can
839       use "undef" as the library to find them.
840
841   Strings
842        use FFI::Platypus 1.00;
843
844        my $ffi = FFI::Platypus->new( api => 1 );
845        $ffi->lib(undef);
846        $ffi->attach(puts => ['string'] => 'int');
847        $ffi->attach(strlen => ['string'] => 'int');
848
849        puts(strlen('somestring'));
850
851        $ffi->attach(strstr => ['string','string'] => 'string');
852
853        puts(strstr('somestring', 'string'));
854
855        #attach puts => [string] => int;
856
857        puts(puts("lol"));
858
859        $ffi->attach(strerror => ['int'] => 'string');
860
861        puts(strerror(2));
862
863       Discussion: ASCII and UTF-8 Strings are not a native type to "libffi"
864       but the are handled seamlessly by Platypus.  If you need to talk to an
865       API that uses so called "wide" strings (APIs which use "const wchar_t*"
866       or "wchar_t*"), then you will want to use the wide string type plugin
867       FFI::Platypus::Type::WideString.  APIs which use other arbitrary
868       encodings can be accessed by converting your Perl strings manually with
869       the Encode module.
870
871   Attach function from pointer
872        use FFI::TinyCC;
873        use FFI::Platypus 1.00;
874
875        my $ffi = FFI::Platypus->new( api => 1 );
876        my $tcc = FFI::TinyCC->new;
877
878        $tcc->compile_string(q{
879          int
880          add(int a, int b)
881          {
882            return a+b;
883          }
884        });
885
886        my $address = $tcc->get_symbol('add');
887
888        $ffi->attach( [ $address => 'add' ] => ['int','int'] => 'int' );
889
890        print add(1,2), "\n";
891
892       Discussion: Sometimes you will have a pointer to a function from a
893       source other than Platypus that you want to call.  You can use that
894       address instead of a function name for either of the function or attach
895       methods.  In this example we use FFI::TinyCC to compile a short piece
896       of C code and to give us the address of one of its functions, which we
897       then use to create a perl xsub to call it.
898
899       FFI::TinyCC embeds the Tiny C Compiler (tcc) to provide a just-in-time
900       (JIT) compilation service for FFI.
901
902   libzmq
903        use constant ZMQ_IO_THREADS  => 1;
904        use constant ZMQ_MAX_SOCKETS => 2;
905        use constant ZMQ_REQ => 3;
906        use constant ZMQ_REP => 4;
907        use FFI::CheckLib qw( find_lib_or_exit );
908        use FFI::Platypus 1.00;
909        use FFI::Platypus::Memory qw( malloc );
910        use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar );
911
912        my $endpoint = "ipc://zmq-ffi-$$";
913        my $ffi = FFI::Platypus->new( api => 1 );
914
915        $ffi->lib(undef); # for puts
916        $ffi->attach(puts => ['string'] => 'int');
917
918        $ffi->lib(find_lib_or_exit lib => 'zmq');
919        $ffi->attach(zmq_version => ['int*', 'int*', 'int*'] => 'void');
920
921        my($major,$minor,$patch);
922        zmq_version(\$major, \$minor, \$patch);
923        puts("libzmq version $major.$minor.$patch");
924        die "this script only works with libzmq 3 or better" unless $major >= 3;
925
926        $ffi->type('opaque'       => 'zmq_context');
927        $ffi->type('opaque'       => 'zmq_socket');
928        $ffi->type('opaque'       => 'zmq_msg_t');
929        $ffi->attach(zmq_ctx_new  => [] => 'zmq_context');
930        $ffi->attach(zmq_ctx_set  => ['zmq_context', 'int', 'int'] => 'int');
931        $ffi->attach(zmq_socket   => ['zmq_context', 'int'] => 'zmq_socket');
932        $ffi->attach(zmq_connect  => ['opaque', 'string'] => 'int');
933        $ffi->attach(zmq_bind     => ['zmq_socket', 'string'] => 'int');
934        $ffi->attach(zmq_send     => ['zmq_socket', 'opaque', 'size_t', 'int'] => 'int');
935        $ffi->attach(zmq_msg_init => ['zmq_msg_t'] => 'int');
936        $ffi->attach(zmq_msg_recv => ['zmq_msg_t', 'zmq_socket', 'int'] => 'int');
937        $ffi->attach(zmq_msg_data => ['zmq_msg_t'] => 'opaque');
938        $ffi->attach(zmq_errno    => [] => 'int');
939        $ffi->attach(zmq_strerror => ['int'] => 'string');
940
941        my $context = zmq_ctx_new();
942        zmq_ctx_set($context, ZMQ_IO_THREADS, 1);
943
944        my $socket1 = zmq_socket($context, ZMQ_REQ);
945        zmq_connect($socket1, $endpoint);
946
947        my $socket2 = zmq_socket($context, ZMQ_REP);
948        zmq_bind($socket2, $endpoint);
949
950        do { # send
951          our $sent_message = "hello there";
952          my($pointer, $size) = scalar_to_buffer $sent_message;
953          my $r = zmq_send($socket1, $pointer, $size, 0);
954          die zmq_strerror(zmq_errno()) if $r == -1;
955        };
956
957        do { # recv
958          my $msg_ptr  = malloc 100;
959          zmq_msg_init($msg_ptr);
960          my $size     = zmq_msg_recv($msg_ptr, $socket2, 0);
961          die zmq_strerror(zmq_errno()) if $size == -1;
962          my $data_ptr = zmq_msg_data($msg_ptr);
963          my $recv_message = buffer_to_scalar $data_ptr, $size;
964          print "recv_message = $recv_message\n";
965        };
966
967       Discussion: ØMQ is a high-performance asynchronous messaging library.
968       There are a few things to note here.
969
970       Firstly, sometimes there may be multiple versions of a library in the
971       wild and you may need to verify that the library on a system meets your
972       needs (alternatively you could support multiple versions and configure
973       your bindings dynamically).  Here we use "zmq_version" to ask libzmq
974       which version it is.
975
976       "zmq_version" returns the version number via three integer pointer
977       arguments, so we use the pointer to integer type: "int *".  In order to
978       pass pointer types, we pass a reference. In this case it is a reference
979       to an undefined value, because zmq_version will write into the pointers
980       the output values, but you can also pass in references to integers,
981       floating point values and opaque pointer types.  When the function
982       returns the $major variable (and the others) has been updated and we
983       can use it to verify that it supports the API that we require.
984
985       Notice that we define three aliases for the "opaque" type:
986       "zmq_context", "zmq_socket" and "zmq_msg_t".  While this isn't strictly
987       necessary, since Platypus and C treat all three of these types the
988       same, it is useful form of documentation that helps describe the
989       functionality of the interface.
990
991       Finally we attach the necessary functions, send and receive a message.
992       If you are interested, there is a fully fleshed out ØMQ Perl interface
993       implemented using FFI called ZMQ::FFI.
994
995   libarchive
996        use FFI::Platypus 1.00;
997        use FFI::CheckLib qw( find_lib_or_exit );
998
999        # This example uses FreeBSD's libarchive to list the contents of any
1000        # archive format that it suppors.  We've also filled out a part of
1001        # the ArchiveWrite class that could be used for writing archive formats
1002        # supported by libarchive
1003
1004        my $ffi = FFI::Platypus->new( api => 1 );
1005        $ffi->lib(find_lib_or_exit lib => 'archive');
1006        $ffi->type('object(Archive)'      => 'archive_t');
1007        $ffi->type('object(ArchiveRead)'  => 'archive_read_t');
1008        $ffi->type('object(ArchiveWrite)' => 'archive_write_t');
1009        $ffi->type('object(ArchiveEntry)' => 'archive_entry_t');
1010
1011        package Archive;
1012
1013        # base class is "abstract" having no constructor or destructor
1014
1015        $ffi->mangler(sub {
1016          my($name) = @_;
1017          "archive_$name";
1018        });
1019        $ffi->attach( error_string => ['archive_t'] => 'string' );
1020
1021        package ArchiveRead;
1022
1023        our @ISA = qw( Archive );
1024
1025        $ffi->mangler(sub {
1026          my($name) = @_;
1027          "archive_read_$name";
1028        });
1029
1030        $ffi->attach( new                   => ['string']                        => 'archive_read_t' );
1031        $ffi->attach( [ free => 'DESTROY' ] => ['archive_t']                     => 'void' );
1032        $ffi->attach( support_filter_all    => ['archive_t']                     => 'int' );
1033        $ffi->attach( support_format_all    => ['archive_t']                     => 'int' );
1034        $ffi->attach( open_filename         => ['archive_t','string','size_t']   => 'int' );
1035        $ffi->attach( next_header2          => ['archive_t', 'archive_entry_t' ] => 'int' );
1036        $ffi->attach( data_skip             => ['archive_t']                     => 'int' );
1037        # ... define additional read methods
1038
1039        package ArchiveWrite;
1040
1041        our @ISA = qw( Archive );
1042
1043        $ffi->mangler(sub {
1044          my($name) = @_;
1045          "archive_write_$name";
1046        });
1047
1048        $ffi->attach( new                   => ['string'] => 'archive_write_t' );
1049        $ffi->attach( [ free => 'DESTROY' ] => ['archive_write_t'] => 'void' );
1050        # ... define additional write methods
1051
1052        package ArchiveEntry;
1053
1054        $ffi->mangler(sub {
1055          my($name) = @_;
1056          "archive_entry_$name";
1057        });
1058
1059        $ffi->attach( new => ['string']     => 'archive_entry_t' );
1060        $ffi->attach( [ free => 'DESTROY' ] => ['archive_entry_t'] => 'void' );
1061        $ffi->attach( pathname              => ['archive_entry_t'] => 'string' );
1062        # ... define additional entry methods
1063
1064        package main;
1065
1066        use constant ARCHIVE_OK => 0;
1067
1068        # this is a Perl version of the C code here:
1069        # https://github.com/libarchive/libarchive/wiki/Examples#List_contents_of_Archive_stored_in_File
1070
1071        my $archive_filename = shift @ARGV;
1072        unless(defined $archive_filename)
1073        {
1074          print "usage: $0 archive.tar\n";
1075          exit;
1076        }
1077
1078        my $archive = ArchiveRead->new;
1079        $archive->support_filter_all;
1080        $archive->support_format_all;
1081
1082        my $r = $archive->open_filename($archive_filename, 1024);
1083        die "error opening $archive_filename: ", $archive->error_string
1084          unless $r == ARCHIVE_OK;
1085
1086        my $entry = ArchiveEntry->new;
1087
1088        while($archive->next_header2($entry) == ARCHIVE_OK)
1089        {
1090          print $entry->pathname, "\n";
1091          $archive->data_skip;
1092        }
1093
1094       Discussion: libarchive is the implementation of "tar" for FreeBSD
1095       provided as a library and available on a number of platforms.
1096
1097       One interesting thing about libarchive is that it provides a kind of
1098       object oriented interface via opaque pointers.  This example creates an
1099       abstract class "Archive", and concrete classes "ArchiveWrite",
1100       "ArchiveRead" and "ArchiveEntry".  The concrete classes can even be
1101       inherited from and extended just like any Perl classes because of the
1102       way the custom types are implemented.  We use Platypus's "object" type
1103       for this implementation, which is a wrapper around an "opaque" (can
1104       also be an integer) type that is blessed into a particular class.
1105
1106       Another advanced feature of this example is that we define a mangler to
1107       modify the symbol resolution for each class.  This means we can do this
1108       when we define a method for Archive:
1109
1110        $ffi->attach( support_filter_all => ['archive_t'] => 'int' );
1111
1112       Rather than this:
1113
1114        $ffi->attach(
1115          [ archive_read_support_filter_all => 'support_read_filter_all' ] =>
1116          ['archive_t'] => 'int' );
1117        );
1118
1119   unix open
1120        use FFI::Platypus 1.00;
1121
1122        {
1123          package FD;
1124
1125          use constant O_RDONLY => 0;
1126          use constant O_WRONLY => 1;
1127          use constant O_RDWR   => 2;
1128
1129          use constant IN  => bless \do { my $in=0  }, __PACKAGE__;
1130          use constant OUT => bless \do { my $out=1 }, __PACKAGE__;
1131          use constant ERR => bless \do { my $err=2 }, __PACKAGE__;
1132
1133          my $ffi = FFI::Platypus->new( api => 1, lib => [undef]);
1134
1135          $ffi->type('object(FD,int)' => 'fd');
1136
1137          $ffi->attach( [ 'open' => 'new' ] => [ 'string', 'int', 'mode_t' ] => 'fd' => sub {
1138            my($xsub, $class, $fn, @rest) = @_;
1139            my $fd = $xsub->($fn, @rest);
1140            die "error opening $fn $!" if $$fd == -1;
1141            $fd;
1142          });
1143
1144          $ffi->attach( write => ['fd', 'string', 'size_t' ] => 'ssize_t' );
1145          $ffi->attach( read  => ['fd', 'string', 'size_t' ] => 'ssize_t' );
1146          $ffi->attach( close => ['fd'] => 'int' );
1147        }
1148
1149        my $fd = FD->new("$0", FD::O_RDONLY);
1150
1151        my $buffer = "\0" x 10;
1152
1153        while(my $br = $fd->read($buffer, 10))
1154        {
1155          FD::OUT->write($buffer, $br);
1156        }
1157
1158        $fd->close;
1159
1160       Discussion: The Unix file system calls use an integer handle for each
1161       open file.  We can use the same "object" type that we used for
1162       libarchive above, except we let platypus know that the underlying type
1163       is "int" instead of "opaque" (the latter being the default for the
1164       "object" type).  Mainly just for demonstration since Perl has much
1165       better IO libraries, but now we have an OO interface to the Unix IO
1166       functions.
1167
1168   bzip2
1169        use FFI::Platypus 1.00;
1170        use FFI::CheckLib qw( find_lib_or_die );
1171        use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar );
1172        use FFI::Platypus::Memory qw( malloc free );
1173
1174        my $ffi = FFI::Platypus->new( api => 1 );
1175        $ffi->lib(find_lib_or_die lib => 'bz2');
1176
1177        $ffi->attach(
1178          [ BZ2_bzBuffToBuffCompress => 'compress' ] => [
1179            'opaque',                           # dest
1180            'unsigned int *',                   # dest length
1181            'opaque',                           # source
1182            'unsigned int',                     # source length
1183            'int',                              # blockSize100k
1184            'int',                              # verbosity
1185            'int',                              # workFactor
1186          ] => 'int',
1187          sub {
1188            my $sub = shift;
1189            my($source,$source_length) = scalar_to_buffer $_[0];
1190            my $dest_length = int(length($source)*1.01) + 1 + 600;
1191            my $dest = malloc $dest_length;
1192            my $r = $sub->($dest, \$dest_length, $source, $source_length, 9, 0, 30);
1193            die "bzip2 error $r" unless $r == 0;
1194            my $compressed = buffer_to_scalar($dest, $dest_length);
1195            free $dest;
1196            $compressed;
1197          },
1198        );
1199
1200        $ffi->attach(
1201          [ BZ2_bzBuffToBuffDecompress => 'decompress' ] => [
1202            'opaque',                           # dest
1203            'unsigned int *',                   # dest length
1204            'opaque',                           # source
1205            'unsigned int',                     # source length
1206            'int',                              # small
1207            'int',                              # verbosity
1208          ] => 'int',
1209          sub {
1210            my $sub = shift;
1211            my($source, $source_length) = scalar_to_buffer $_[0];
1212            my $dest_length = $_[1];
1213            my $dest = malloc $dest_length;
1214            my $r = $sub->($dest, \$dest_length, $source, $source_length, 0, 0);
1215            die "bzip2 error $r" unless $r == 0;
1216            my $decompressed = buffer_to_scalar($dest, $dest_length);
1217            free $dest;
1218            $decompressed;
1219          },
1220        );
1221
1222        my $original = "hello compression world\n";
1223        my $compressed = compress($original);
1224        print decompress($compressed, length $original);
1225
1226       Discussion: bzip2 is a compression library.  For simple one shot
1227       attempts at compression/decompression when you expect the original and
1228       the result to fit within memory it provides two convenience functions
1229       "BZ2_bzBuffToBuffCompress" and "BZ2_bzBuffToBuffDecompress".
1230
1231       The first four arguments of both of these C functions are identical,
1232       and represent two buffers.  One buffer is the source, the second is the
1233       destination.  For the destination, the length is passed in as a pointer
1234       to an integer.  On input this integer is the size of the destination
1235       buffer, and thus the maximum size of the compressed or decompressed
1236       data.  When the function returns the actual size of compressed or
1237       compressed data is stored in this integer.
1238
1239       This is normal stuff for C, but in Perl our buffers are scalars and
1240       they already know how large they are.  In this sort of situation,
1241       wrapping the C function in some Perl code can make your interface a
1242       little more Perl like.  In order to do this, just provide a code
1243       reference as the last argument to the "attach" method.  The first
1244       argument to this wrapper will be a code reference to the C function.
1245       The Perl arguments will come in after that.  This allows you to modify
1246       / convert the arguments to conform to the C API.  What ever value you
1247       return from the wrapper function will be returned back to the original
1248       caller.
1249
1250   The Win32 API
1251        use utf8;
1252        use FFI::Platypus 1.00;
1253
1254        my $ffi = FFI::Platypus->new(
1255          api  => 1,
1256          lib  => [undef],
1257        );
1258
1259        # see FFI::Platypus::Lang::Win32
1260        $ffi->lang('Win32');
1261
1262        # Send a Unicode string to the Windows API MessageBoxW function.
1263        use constant MB_OK                   => 0x00000000;
1264        use constant MB_DEFAULT_DESKTOP_ONLY => 0x00020000;
1265        $ffi->attach( [MessageBoxW => 'MessageBox'] => [ 'HWND', 'LPCWSTR', 'LPCWSTR', 'UINT'] => 'int' );
1266        MessageBox(undef, "I ❤️ Platypus", "Confession", MB_OK|MB_DEFAULT_DESKTOP_ONLY);
1267
1268       Discussion: The API used by Microsoft Windows present some unique
1269       challenges.  On 32 bit systems a different ABI is used than what is
1270       used by the standard C library.  It also provides a rats nest of type
1271       aliases.  Finally if you want to talk Unicode to any of the Windows API
1272       you will need to use "UTF-16LE" instead of "utf-8" which is native to
1273       Perl.  (The Win32 API refers to these as "LPWSTR" and "LPCWSTR" types).
1274       As much as possible the Win32 "language" plugin attempts to handle this
1275       transparently.  For more details see FFI::Platypus::Lang::Win32.
1276
1277   bundle your own code
1278       "ffi/foo.c":
1279
1280        #include <ffi_platypus_bundle.h>
1281        #include <string.h>
1282
1283        typedef struct {
1284          char *name;
1285          int value;
1286        } foo_t;
1287
1288        foo_t*
1289        foo__new(const char *class_name, const char *name, int value)
1290        {
1291          (void)class_name;
1292          foo_t *self = malloc( sizeof( foo_t ) );
1293          self->name = strdup(name);
1294          self->value = value;
1295          return self;
1296        }
1297
1298        const char *
1299        foo__name(foo_t *self)
1300        {
1301          return self->name;
1302        }
1303
1304        int
1305        foo__value(foo_t *self)
1306        {
1307          return self->value;
1308        }
1309
1310        void
1311        foo__DESTROY(foo_t *self)
1312        {
1313          free(self->name);
1314          free(self);
1315        }
1316
1317       "lib/Foo.pm":
1318
1319        package Foo;
1320
1321        use strict;
1322        use warnings;
1323        use FFI::Platypus 1.00;
1324
1325        {
1326          my $ffi = FFI::Platypus->new( api => 1 );
1327
1328          $ffi->type('object(Foo)' => 'foo_t');
1329          $ffi->mangler(sub {
1330            my $name = shift;
1331            $name =~ s/^/foo__/;
1332            $name;
1333          });
1334
1335          $ffi->bundle;
1336
1337          $ffi->attach( new =>     [ 'string', 'string', 'int' ] => 'foo_t'  );
1338          $ffi->attach( name =>    [ 'foo_t' ]                   => 'string' );
1339          $ffi->attach( value =>   [ 'foo_t' ]                   => 'int'    );
1340          $ffi->attach( DESTROY => [ 'foo_t' ]                   => 'void'   );
1341        }
1342
1343        1;
1344
1345       You can bundle your own C (or other compiled language) code with your
1346       Perl extension.  Sometimes this is helpful for smoothing over the
1347       interface of a C library which is not very FFI friendly.  Sometimes you
1348       may want to write some code in C for a tight loop.  Either way, you can
1349       do this with the Platypus bundle interface.  See FFI::Platypus::Bundle
1350       for more details.
1351
1352       Also related is the bundle constant interface, which allows you to
1353       define Perl constants in C space.  See FFI::Platypus::Constant for
1354       details.
1355

FAQ

1357   How do I get constants defined as macros in C header files
1358       This turns out to be a challenge for any language calling into C, which
1359       frequently uses "#define" macros to define constants like so:
1360
1361        #define FOO_STATIC  1
1362        #define FOO_DYNAMIC 2
1363        #define FOO_OTHER   3
1364
1365       As macros are expanded and their definitions are thrown away by the C
1366       pre-processor there isn't any way to get the name/value mappings from
1367       the compiled dynamic library.
1368
1369       You can manually create equivalent constants in your Perl source:
1370
1371        use constant FOO_STATIC  => 1;
1372        use constant FOO_DYNAMIC => 2;
1373        use constant FOO_OTHER   => 3;
1374
1375       If there are a lot of these types of constants you might want to
1376       consider using a tool (Convert::Binary::C can do this) that can extract
1377       the constants for you.
1378
1379       See also the "Integer constants" example in FFI::Platypus::Type.
1380
1381       You can also use the new Platypus bundle interface to define Perl
1382       constants from C space.  This is more reliable, but does require a
1383       compiler at install time.  It is recommended mainly for writing
1384       bindings against libraries that have constants that can vary widely
1385       from platform to platform.  See FFI::Platypus::Constant for details.
1386
1387   What about enums?
1388       The C enum types are integers.  The underlying type is up to the
1389       platform, so Platypus provides "enum" and "senum" types for unsigned
1390       and singed enums respectively.  At least some compilers treat signed
1391       and unsigned enums as different types.  The enum values are essentially
1392       the same as macro constants described above from an FFI perspective.
1393       Thus the process of defining enum values is identical to the process of
1394       defining macro constants in Perl.
1395
1396       For more details on enumerated types see "Enum types" in
1397       FFI::Platypus::Type.
1398
1399       There is also a type plugin (FFI::Platypus::Type::Enum) that can be
1400       helpful in writing interfaces that use enums.
1401
1402   Memory leaks
1403       There are a couple places where memory is allocated, but never
1404       deallocated that may look like memory leaks by tools designed to find
1405       memory leaks like valgrind.  This memory is intended to be used for the
1406       lifetime of the perl process so there normally this isn't a problem
1407       unless you are embedding a Perl interpreter which doesn't closely match
1408       the lifetime of your overall application.
1409
1410       Specifically:
1411
1412       type cache
1413           some types are cached and not freed.  These are needed as long as
1414           there are FFI functions that could be called.
1415
1416       attached functions
1417           Attaching a function as an xsub will definitely allocate memory
1418           that won't be freed because the xsub could be called at any time,
1419           including in "END" blocks.
1420
1421       The Platypus team plans on adding a hook to free some of this "leaked"
1422       memory for use cases where Perl and Platypus are embedded in a larger
1423       application where the lifetime of the Perl process is significantly
1424       smaller than the overall lifetime of the whole process.
1425
1426   I get seg faults on some platforms but not others with a library using
1427       pthreads.
1428       On some platforms, Perl isn't linked with "libpthreads" if Perl threads
1429       are not enabled.  On some platforms this doesn't seem to matter,
1430       "libpthreads" can be loaded at runtime without much ill-effect.  (Linux
1431       from my experience doesn't seem to mind one way or the other).  Some
1432       platforms are not happy about this, and about the only thing that you
1433       can do about it is to build Perl such that it links with "libpthreads"
1434       even if it isn't a threaded Perl.
1435
1436       This is not really an FFI issue, but a Perl issue, as you will have the
1437       same problem writing XS code for the such libraries.
1438
1439   Doesn't work on Perl 5.10.0.
1440       I try as best as possible to support the same range of Perls as the
1441       Perl toolchain.  That means all the way back to 5.8.1.  Unfortunately,
1442       5.10.0 seems to have a problem that is difficult to diagnose.  Patches
1443       to fix are welcome, if you want to help out on this, please see:
1444
1445       <https://github.com/PerlFFI/FFI-Platypus/issues/68>
1446
1447       Since this is an older buggy version of Perl it is recommended that you
1448       instead upgrade to 5.10.1 or later.
1449

CAVEATS

1451       Platypus and Native Interfaces like libffi rely on the availability of
1452       dynamic libraries.  Things not supported include:
1453
1454       Systems that lack dynamic library support
1455           Like MS-DOS
1456
1457       Systems that are not supported by libffi
1458           Like OpenVMS
1459
1460       Languages that do not support using dynamic libraries from other
1461       languages
1462           Like older versions of Google's Go. This is a problem for C / XS
1463           code as well.
1464
1465       Languages that do not compile to machine code
1466           Like .NET based languages and Java.
1467
1468       The documentation has a bias toward using FFI / Platypus with C.  This
1469       is my fault, as my background in mainly in C/C++ programmer (when I am
1470       not writing Perl).  In many places I use "C" as a short form for "any
1471       language that can generate machine code and is callable from C".  I
1472       welcome pull requests to the Platypus core to address this issue.  In
1473       an attempt to ease usage of Platypus by non C programmers, I have
1474       written a number of foreign language plugins for various popular
1475       languages (see the SEE ALSO below).  These plugins come with examples
1476       specific to those languages, and documentation on common issues related
1477       to using those languages with FFI.  In most cases these are available
1478       for easy adoption for those with the know-how or the willingness to
1479       learn.  If your language doesn't have a plugin YET, that is just
1480       because you haven't written it yet.
1481

SUPPORT

1483       IRC: #native on irc.perl.org
1484
1485       (click for instant chat room login)
1486       <http://chat.mibbit.com/#native@irc.perl.org>
1487
1488       If something does not work the way you think it should, or if you have
1489       a feature request, please open an issue on this project's GitHub Issue
1490       tracker:
1491
1492       <https://github.com/perlFFI/FFI-Platypus/issues>
1493

CONTRIBUTING

1495       If you have implemented a new feature or fixed a bug then you may make
1496       a pull request on this project's GitHub repository:
1497
1498       <https://github.com/PerlFFI/FFI-Platypus/pulls>
1499
1500       This project is developed using Dist::Zilla.  The project's git
1501       repository also comes with the "Makefile.PL" file necessary for
1502       building, testing (and even installing if necessary) without
1503       Dist::Zilla.  Please keep in mind though that these files are generated
1504       so if changes need to be made to those files they should be done
1505       through the project's "dist.ini" file.  If you do use Dist::Zilla and
1506       already have the necessary plugins installed, then I encourage you to
1507       run "dzil test" before making any pull requests.  This is not a
1508       requirement, however, I am happy to integrate especially smaller
1509       patches that need tweaking to fit the project standards.  I may push
1510       back and ask you to write a test case or alter the formatting of a
1511       patch depending on the amount of time I have and the amount of code
1512       that your patch touches.
1513
1514       This project's GitHub issue tracker listed above is not Write-Only.  If
1515       you want to contribute then feel free to browse through the existing
1516       issues and see if there is something you feel you might be good at and
1517       take a whack at the problem.  I frequently open issues myself that I
1518       hope will be accomplished by someone in the future but do not have time
1519       to immediately implement myself.
1520
1521       Another good area to help out in is documentation.  I try to make sure
1522       that there is good document coverage, that is there should be
1523       documentation describing all the public features and warnings about
1524       common pitfalls, but an outsider's or alternate view point on such
1525       things would be welcome; if you see something confusing or lacks
1526       sufficient detail I encourage documentation only pull requests to
1527       improve things.
1528
1529       The Platypus distribution comes with a test library named "libtest"
1530       that is normally automatically built by "./Build test".  If you prefer
1531       to use "prove" or run tests directly, you can use the "./Build libtest"
1532       command to build it.  Example:
1533
1534        % perl Makefile.PL
1535        % make
1536        % make ffi-test
1537        % prove -bv t
1538        # or an individual test
1539        % perl -Mblib t/ffi_platypus_memory.t
1540
1541       The build process also respects these environment variables:
1542
1543       FFI_PLATYPUS_DEBUG_FAKE32
1544           When building Platypus on 32 bit Perls, it will use the Math::Int64
1545           C API and make Math::Int64 a prerequisite.  Setting this
1546           environment variable will force Platypus to build with both of
1547           those options on a 64 bit Perl as well.
1548
1549            % env FFI_PLATYPUS_DEBUG_FAKE32=1 perl Makefile.PL
1550            DEBUG_FAKE32:
1551              + making Math::Int64 a prereq
1552              + Using Math::Int64's C API to manipulate 64 bit values
1553            Generating a Unix-style Makefile
1554            Writing Makefile for FFI::Platypus
1555            Writing MYMETA.yml and MYMETA.json
1556            %
1557
1558       FFI_PLATYPUS_NO_ALLOCA
1559           Platypus uses the non-standard and somewhat controversial C
1560           function "alloca" by default on platforms that support it.  I
1561           believe that Platypus uses it responsibly to allocate small amounts
1562           of memory for argument type parameters, and does not use it to
1563           allocate large structures like arrays or buffers.  If you prefer
1564           not to use "alloca" despite these precautions, then you can turn
1565           its use off by setting this environment variable when you run
1566           "Makefile.PL":
1567
1568            helix% env FFI_PLATYPUS_NO_ALLOCA=1 perl Makefile.PL
1569            NO_ALLOCA:
1570              + alloca() will not be used, even if your platform supports it.
1571            Generating a Unix-style Makefile
1572            Writing Makefile for FFI::Platypus
1573            Writing MYMETA.yml and MYMETA.json
1574
1575       V   When building platypus may hide some of the excessive output when
1576           probing and building, unless you set "V" to a true value.
1577
1578            % env V=1 perl Makefile.PL
1579            % make V=1
1580            ...
1581
1582   Coding Guidelines
1583       •   Do not hesitate to make code contribution.  Making useful
1584           contributions is more important than following byzantine
1585           bureaucratic coding regulations.  We can always tweak things later.
1586
1587       •   Please make an effort to follow existing coding style when making
1588           pull requests.
1589
1590       •   Platypus supports all production Perl releases since 5.8.1.  For
1591           that reason, please do not introduce any code that requires a newer
1592           version of Perl.
1593
1594   Performance Testing
1595       As Mark Twain was fond of saying there are four types of lies: lies,
1596       damn lies, statistics and benchmarks.  That being said, it can
1597       sometimes be helpful to compare the runtime performance of Platypus if
1598       you are making significant changes to the Platypus Core.  For that I
1599       use `FFI-Performance`, which can be found in my GitHub repository here:
1600
1601       <https://github.com/PerlFFI/FFI-Performance>
1602
1603   System integrators
1604       This distribution uses Alien::FFI in fallback mode, meaning if the
1605       system doesn't provide "pkg-config" and "libffi" it will attempt to
1606       download "libffi" and build it from source.  If you are including
1607       Platypus in a larger system (for example a Linux distribution) you only
1608       need to make sure to declare "pkg-config" or "pkgconf" and the
1609       development package for "libffi" as prereqs for this module.
1610

SEE ALSO

1612       NativeCall
1613           Promising interface to Platypus inspired by Perl 6.
1614
1615       FFI::Platypus::Type
1616           Type definitions for Platypus.
1617
1618       FFI::Platypus::Record
1619           Define structured data records (C "structs") for use with Platypus.
1620
1621       FFI::C
1622           Another interface for defining structured data records for use with
1623           Platypus.  Its advantage over FFI::Platypus::Record is that it
1624           supports "union"s and nested data structures.  Its disadvantage is
1625           that it doesn't support passing "struct"s by-value.
1626
1627       FFI::Platypus::API
1628           The custom types API for Platypus.
1629
1630       FFI::Platypus::Memory
1631           Memory functions for FFI.
1632
1633       FFI::CheckLib
1634           Find dynamic libraries in a portable way.
1635
1636       FFI::TinyCC
1637           JIT compiler for FFI.
1638
1639       FFI::Platypus::Lang::C
1640           Documentation and tools for using Platypus with the C programming
1641           language
1642
1643       FFI::Platypus::Lang::CPP
1644           Documentation and tools for using Platypus with the C++ programming
1645           language
1646
1647       FFI::Platypus::Lang::Fortran
1648           Documentation and tools for using Platypus with Fortran
1649
1650       FFI::Platypus::Lang::Go
1651           Documentation and tools for using Platypus with Go
1652
1653       FFI::Platypus::Lang::Pascal
1654           Documentation and tools for using Platypus with Free Pascal
1655
1656       FFI::Platypus::Lang::Rust
1657           Documentation and tools for using Platypus with the Rust
1658           programming language
1659
1660       FFI::Platypus::Lang::ASM
1661           Documentation and tools for using Platypus with the Assembly
1662
1663       FFI::Platypus::Lang::Win32
1664           Documentation and tools for using Platypus with the Win32 API.
1665
1666       Wasm and Wasm::Wasmtime
1667           Modules for writing WebAssembly bindings in Perl.  This allows you
1668           to call functions written in any language supported by WebAssembly.
1669           These modules are also implemented using Platypus.
1670
1671       Convert::Binary::C
1672           A great interface for decoding C data structures, including
1673           "struct"s, "enum"s, "#define"s and more.
1674
1675       pack and unpack
1676           Native to Perl functions that can be used to decode C "struct"
1677           types.
1678
1679       C::Scan
1680           This module can extract constants and other useful objects from C
1681           header files that may be relevant to an FFI application.  One
1682           downside is that its use may require development packages to be
1683           installed.
1684
1685       Win32::API
1686           Microsoft Windows specific FFI style interface.
1687
1688       Ctypes <https://gitorious.org/perl-ctypes>
1689           Ctypes was intended as a FFI style interface for Perl, but was
1690           never part of CPAN, and at least the last time I tried it did not
1691           work with recent versions of Perl.
1692
1693       FFI Older, simpler, less featureful FFI.  It used to be implemented
1694           using FSF's "ffcall".  Because "ffcall" has been unsupported for
1695           some time, I reimplemented this module using FFI::Platypus.
1696
1697       C::DynaLib
1698           Another FFI for Perl that doesn't appear to have worked for a long
1699           time.
1700
1701       C::Blocks
1702           Embed a tiny C compiler into your Perl scripts.
1703
1704       Alien::FFI
1705           Provides libffi for Platypus during its configuration and build
1706           stages.
1707
1708       P5NCI
1709           Yet another FFI like interface that does not appear to be supported
1710           or under development anymore.
1711

ACKNOWLEDGMENTS

1713       In addition to the contributors mentioned below, I would like to
1714       acknowledge Brock Wilcox (AWWAIID) and Meredith Howard (MHOWARD) whose
1715       work on "FFI::Sweet" not only helped me get started with FFI but
1716       significantly influenced the design of Platypus.
1717
1718       Dan Book, who goes by Grinnz on IRC for answering user questions about
1719       FFI and Platypus.
1720
1721       In addition I'd like to thank Alessandro Ghedini (ALEXBIO) whose work
1722       on another Perl FFI library helped drive some of the development ideas
1723       for FFI::Platypus.
1724

AUTHOR

1726       Author: Graham Ollis <plicease@cpan.org>
1727
1728       Contributors:
1729
1730       Bakkiaraj Murugesan (bakkiaraj)
1731
1732       Dylan Cali (calid)
1733
1734       pipcet
1735
1736       Zaki Mughal (zmughal)
1737
1738       Fitz Elliott (felliott)
1739
1740       Vickenty Fesunov (vyf)
1741
1742       Gregor Herrmann (gregoa)
1743
1744       Shlomi Fish (shlomif)
1745
1746       Damyan Ivanov
1747
1748       Ilya Pavlov (Ilya33)
1749
1750       Petr Pisar (ppisar)
1751
1752       Mohammad S Anwar (MANWAR)
1753
1754       Håkon Hægland (hakonhagland, HAKONH)
1755
1756       Meredith (merrilymeredith, MHOWARD)
1757
1758       Diab Jerius (DJERIUS)
1759
1760       Eric Brine (IKEGAMI)
1761
1762       szTheory
1763
1765       This software is copyright (c) 2015,2016,2017,2018,2019,2020 by Graham
1766       Ollis.
1767
1768       This is free software; you can redistribute it and/or modify it under
1769       the same terms as the Perl 5 programming language system itself.
1770
1771
1772
1773perl v5.32.1                      2021-03-18                  FFI::Platypus(3)
Impressum