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.56
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 Raku
50           One of those "other" languages could be Raku and Raku already has
51           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 [version 0.91]
117
118           Sets the API level.  Legal values are
119
120           0   Original API level.  See FFI::Platypus::TypeParser::Version0
121               for details on the differences.
122
123           1   Enable the next generation type parser which allows pass-by-
124               value records and type decoration on basic types.  Using API
125               level 1 prior to Platypus version 1.00 will trigger a (noisy)
126               warning.
127
128               All new code should be written with this set to 1!  The
129               Platypus documentation assumes this api level is set.
130
131           2   Enable version 2 API, which is currently experimental.  Using
132               API level 2 prior to Platypus version 2.00 will trigger a
133               (noisy) warning.
134
135               API version 2 is identical to version 1, except:
136
137               Pointer functions that return "NULL" will return "undef"
138               instead of empty list
139                   This fixes a long standing design bug in Platypus.
140
141               Array references may be passed to pointer argument types
142                   This replicates the behavior of array argument types with
143                   no size.  So the types "sint8*" and "sint8[]" behave
144                   identically when an array reference is passed in.  They
145                   differ in that, as before, you can pass a scalar reference
146                   into type "sint8*".
147
148       lib Either a pathname (string) or a list of pathnames (array ref of
149           strings) to pre-populate the lib attribute.  Use "[undef]" to
150           search the current process for symbols.
151
152           0.48
153
154           "undef" (without the array reference) can be used to search the
155           current process for symbols.
156
157       ignore_not_found
158           [version 0.15]
159
160           Set the ignore_not_found attribute.
161
162       lang
163           [version 0.18]
164
165           Set the lang attribute.
166

ATTRIBUTES

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

METHODS

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

EXAMPLES

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

FAQ

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

CAVEATS

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

SUPPORT

1502       IRC: #native on irc.perl.org
1503
1504       (click for instant chat room login)
1505       <http://chat.mibbit.com/#native@irc.perl.org>
1506
1507       If something does not work the way you think it should, or if you have
1508       a feature request, please open an issue on this project's GitHub Issue
1509       tracker:
1510
1511       <https://github.com/perlFFI/FFI-Platypus/issues>
1512

CONTRIBUTING

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

SEE ALSO

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

ACKNOWLEDGMENTS

1732       In addition to the contributors mentioned below, I would like to
1733       acknowledge Brock Wilcox (AWWAIID) and Meredith Howard (MHOWARD) whose
1734       work on "FFI::Sweet" not only helped me get started with FFI but
1735       significantly influenced the design of Platypus.
1736
1737       Dan Book, who goes by Grinnz on IRC for answering user questions about
1738       FFI and Platypus.
1739
1740       In addition I'd like to thank Alessandro Ghedini (ALEXBIO) whose work
1741       on another Perl FFI library helped drive some of the development ideas
1742       for FFI::Platypus.
1743

AUTHOR

1745       Author: Graham Ollis <plicease@cpan.org>
1746
1747       Contributors:
1748
1749       Bakkiaraj Murugesan (bakkiaraj)
1750
1751       Dylan Cali (calid)
1752
1753       pipcet
1754
1755       Zaki Mughal (zmughal)
1756
1757       Fitz Elliott (felliott)
1758
1759       Vickenty Fesunov (vyf)
1760
1761       Gregor Herrmann (gregoa)
1762
1763       Shlomi Fish (shlomif)
1764
1765       Damyan Ivanov
1766
1767       Ilya Pavlov (Ilya33)
1768
1769       Petr Písař (ppisar)
1770
1771       Mohammad S Anwar (MANWAR)
1772
1773       Håkon Hægland (hakonhagland, HAKONH)
1774
1775       Meredith (merrilymeredith, MHOWARD)
1776
1777       Diab Jerius (DJERIUS)
1778
1779       Eric Brine (IKEGAMI)
1780
1781       szTheory
1782
1783       José Joaquín Atria (JJATRIA)
1784
1785       Pete Houston (openstrike, HOUSTON)
1786
1788       This software is copyright (c) 2015,2016,2017,2018,2019,2020 by Graham
1789       Ollis.
1790
1791       This is free software; you can redistribute it and/or modify it under
1792       the same terms as the Perl 5 programming language system itself.
1793
1794
1795
1796perl v5.34.0                      2021-10-29                  FFI::Platypus(3)
Impressum