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.32
11

SYNOPSIS

13        use FFI::Platypus;
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');            # oly 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_functon');
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_functon_name', ['int', 'string'] => 'string');
403        $ffi->attach(['my_c_functon_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;
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;
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;
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;
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 16;  # uuid_t
785        uuid_generate($uuid);
786
787        my $string = "\0" x 37; # 36 bytes to store a UUID string
788                                # + NUL termination
789        uuid_unparse($uuid, $string);
790
791        print "$string\n";
792
793       Discussion: libuuid is a library used to generate unique identifiers
794       (UUID) for objects that may be accessible beyond the local system.  The
795       library is or was part of the Linux e2fsprogs package.
796
797       Knowing the size of objects is sometimes important.  In this example,
798       we use the sizeof function to get the size of 16 characters (in this
799       case it is simply 16 bytes).  We also know that the strings "deparsed"
800       by "uuid_unparse" are exactly 37 bytes.
801
802   puts and getpid
803        use FFI::Platypus;
804
805        my $ffi = FFI::Platypus->new( api => 1 );
806        $ffi->lib(undef);
807
808        $ffi->attach(puts => ['string'] => 'int');
809        $ffi->attach(getpid => [] => 'int');
810
811        puts(getpid());
812
813       Discussion: "puts" is part of standard C library on all platforms.
814       "getpid" is available on Unix type platforms.
815
816   Math library
817        use FFI::Platypus;
818        use FFI::CheckLib;
819
820        my $ffi = FFI::Platypus->new( api => 1 );
821        $ffi->lib(undef);
822        $ffi->attach(puts => ['string'] => 'int');
823        $ffi->attach(fdim => ['double','double'] => 'double');
824
825        puts(fdim(7.0, 2.0));
826
827        $ffi->attach(cos => ['double'] => 'double');
828
829        puts(cos(2.0));
830
831        $ffi->attach(fmax => ['double', 'double'] => 'double');
832
833        puts(fmax(2.0,3.0));
834
835       Discussion: On UNIX the standard c library math functions are
836       frequently provided in a separate library "libm", so you could search
837       for those symbols in "libm.so", but that won't work on non-UNIX
838       platforms like Microsoft Windows.  Fortunately Perl uses the math
839       library so these symbols are already in the current process so you can
840       use "undef" as the library to find them.
841
842   Strings
843        use FFI::Platypus;
844
845        my $ffi = FFI::Platypus->new;
846        $ffi->lib(undef);
847        $ffi->attach(puts => ['string'] => 'int');
848        $ffi->attach(strlen => ['string'] => 'int');
849
850        puts(strlen('somestring'));
851
852        $ffi->attach(strstr => ['string','string'] => 'string');
853
854        puts(strstr('somestring', 'string'));
855
856        #attach puts => [string] => int;
857
858        puts(puts("lol"));
859
860        $ffi->attach(strerror => ['int'] => 'string');
861
862        puts(strerror(2));
863
864       Discussion: Strings are not a native type to "libffi" but the are
865       handled seamlessly by Platypus.
866
867   Attach function from pointer
868        use FFI::TinyCC;
869        use FFI::Platypus;
870
871        my $ffi = FFI::Platypus->new( api => 1 );
872        my $tcc = FFI::TinyCC->new;
873
874        $tcc->compile_string(q{
875          int
876          add(int a, int b)
877          {
878            return a+b;
879          }
880        });
881
882        my $address = $tcc->get_symbol('add');
883
884        $ffi->attach( [ $address => 'add' ] => ['int','int'] => 'int' );
885
886        print add(1,2), "\n";
887
888       Discussion: Sometimes you will have a pointer to a function from a
889       source other than Platypus that you want to call.  You can use that
890       address instead of a function name for either of the function or attach
891       methods.  In this example we use FFI::TinyCC to compile a short piece
892       of C code and to give us the address of one of its functions, which we
893       then use to create a perl xsub to call it.
894
895       FFI::TinyCC embeds the Tiny C Compiler (tcc) to provide a just-in-time
896       (JIT) compilation service for FFI.
897
898   libzmq
899        use constant ZMQ_IO_THREADS  => 1;
900        use constant ZMQ_MAX_SOCKETS => 2;
901        use constant ZMQ_REQ => 3;
902        use constant ZMQ_REP => 4;
903        use FFI::CheckLib qw( find_lib_or_exit );
904        use FFI::Platypus;
905        use FFI::Platypus::Memory qw( malloc );
906        use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar );
907
908        my $endpoint = "ipc://zmq-ffi-$$";
909        my $ffi = FFI::Platypus->new( api => 1 );
910
911        $ffi->lib(undef); # for puts
912        $ffi->attach(puts => ['string'] => 'int');
913
914        $ffi->lib(find_lib_or_exit lib => 'zmq');
915        $ffi->attach(zmq_version => ['int*', 'int*', 'int*'] => 'void');
916
917        my($major,$minor,$patch);
918        zmq_version(\$major, \$minor, \$patch);
919        puts("libzmq version $major.$minor.$patch");
920        die "this script only works with libzmq 3 or better" unless $major >= 3;
921
922        $ffi->type('opaque'       => 'zmq_context');
923        $ffi->type('opaque'       => 'zmq_socket');
924        $ffi->type('opaque'       => 'zmq_msg_t');
925        $ffi->attach(zmq_ctx_new  => [] => 'zmq_context');
926        $ffi->attach(zmq_ctx_set  => ['zmq_context', 'int', 'int'] => 'int');
927        $ffi->attach(zmq_socket   => ['zmq_context', 'int'] => 'zmq_socket');
928        $ffi->attach(zmq_connect  => ['opaque', 'string'] => 'int');
929        $ffi->attach(zmq_bind     => ['zmq_socket', 'string'] => 'int');
930        $ffi->attach(zmq_send     => ['zmq_socket', 'opaque', 'size_t', 'int'] => 'int');
931        $ffi->attach(zmq_msg_init => ['zmq_msg_t'] => 'int');
932        $ffi->attach(zmq_msg_recv => ['zmq_msg_t', 'zmq_socket', 'int'] => 'int');
933        $ffi->attach(zmq_msg_data => ['zmq_msg_t'] => 'opaque');
934        $ffi->attach(zmq_errno    => [] => 'int');
935        $ffi->attach(zmq_strerror => ['int'] => 'string');
936
937        my $context = zmq_ctx_new();
938        zmq_ctx_set($context, ZMQ_IO_THREADS, 1);
939
940        my $socket1 = zmq_socket($context, ZMQ_REQ);
941        zmq_connect($socket1, $endpoint);
942
943        my $socket2 = zmq_socket($context, ZMQ_REP);
944        zmq_bind($socket2, $endpoint);
945
946        do { # send
947          our $sent_message = "hello there";
948          my($pointer, $size) = scalar_to_buffer $sent_message;
949          my $r = zmq_send($socket1, $pointer, $size, 0);
950          die zmq_strerror(zmq_errno()) if $r == -1;
951        };
952
953        do { # recv
954          my $msg_ptr  = malloc 100;
955          zmq_msg_init($msg_ptr);
956          my $size     = zmq_msg_recv($msg_ptr, $socket2, 0);
957          die zmq_strerror(zmq_errno()) if $size == -1;
958          my $data_ptr = zmq_msg_data($msg_ptr);
959          my $recv_message = buffer_to_scalar $data_ptr, $size;
960          print "recv_message = $recv_message\n";
961        };
962
963       Discussion: ØMQ is a high-performance asynchronous messaging library.
964       There are a few things to note here.
965
966       Firstly, sometimes there may be multiple versions of a library in the
967       wild and you may need to verify that the library on a system meets your
968       needs (alternatively you could support multiple versions and configure
969       your bindings dynamically).  Here we use "zmq_version" to ask libzmq
970       which version it is.
971
972       "zmq_version" returns the version number via three integer pointer
973       arguments, so we use the pointer to integer type: "int *".  In order to
974       pass pointer types, we pass a reference. In this case it is a reference
975       to an undefined value, because zmq_version will write into the pointers
976       the output values, but you can also pass in references to integers,
977       floating point values and opaque pointer types.  When the function
978       returns the $major variable (and the others) has been updated and we
979       can use it to verify that it supports the API that we require.
980
981       Notice that we define three aliases for the "opaque" type:
982       "zmq_context", "zmq_socket" and "zmq_msg_t".  While this isn't strictly
983       necessary, since Platypus and C treat all three of these types the
984       same, it is useful form of documentation that helps describe the
985       functionality of the interface.
986
987       Finally we attach the necessary functions, send and receive a message.
988       If you are interested, there is a fully fleshed out ØMQ Perl interface
989       implemented using FFI called ZMQ::FFI.
990
991   libarchive
992        use FFI::Platypus      ();
993        use FFI::CheckLib      qw( find_lib_or_exit );
994
995        # This example uses FreeBSD's libarchive to list the contents of any
996        # archive format that it suppors.  We've also filled out a part of
997        # the ArchiveWrite class that could be used for writing archive formats
998        # supported by libarchive
999
1000        my $ffi = FFI::Platypus->new( api => 1 );
1001        $ffi->lib(find_lib_or_exit lib => 'archive');
1002        $ffi->type('object(Archive)'      => 'archive_t');
1003        $ffi->type('object(ArchiveRead)'  => 'archive_read_t');
1004        $ffi->type('object(ArchiveWrite)' => 'archive_write_t');
1005        $ffi->type('object(ArchiveEntry)' => 'archive_entry_t');
1006
1007        package Archive;
1008
1009        # base class is "abstract" having no constructor or destructor
1010
1011        $ffi->mangler(sub {
1012          my($name) = @_;
1013          "archive_$name";
1014        });
1015        $ffi->attach( error_string => ['archive_t'] => 'string' );
1016
1017        package ArchiveRead;
1018
1019        our @ISA = qw( Archive );
1020
1021        $ffi->mangler(sub {
1022          my($name) = @_;
1023          "archive_read_$name";
1024        });
1025
1026        $ffi->attach( new                   => ['string']                        => 'archive_read_t' );
1027        $ffi->attach( [ free => 'DESTROY' ] => ['archive_t']                     => 'void' );
1028        $ffi->attach( support_filter_all    => ['archive_t']                     => 'int' );
1029        $ffi->attach( support_format_all    => ['archive_t']                     => 'int' );
1030        $ffi->attach( open_filename         => ['archive_t','string','size_t']   => 'int' );
1031        $ffi->attach( next_header2          => ['archive_t', 'archive_entry_t' ] => 'int' );
1032        $ffi->attach( data_skip             => ['archive_t']                     => 'int' );
1033        # ... define additional read methods
1034
1035        package ArchiveWrite;
1036
1037        our @ISA = qw( Archive );
1038
1039        $ffi->mangler(sub {
1040          my($name) = @_;
1041          "archive_write_$name";
1042        });
1043
1044        $ffi->attach( new                   => ['string'] => 'archive_write_t' );
1045        $ffi->attach( [ free => 'DESTROY' ] => ['archive_write_t'] => 'void' );
1046        # ... define additional write methods
1047
1048        package ArchiveEntry;
1049
1050        $ffi->mangler(sub {
1051          my($name) = @_;
1052          "archive_entry_$name";
1053        });
1054
1055        $ffi->attach( new => ['string']     => 'archive_entry_t' );
1056        $ffi->attach( [ free => 'DESTROY' ] => ['archive_entry_t'] => 'void' );
1057        $ffi->attach( pathname              => ['archive_entry_t'] => 'string' );
1058        # ... define additional entry methods
1059
1060        package main;
1061
1062        use constant ARCHIVE_OK => 0;
1063
1064        # this is a Perl version of the C code here:
1065        # https://github.com/libarchive/libarchive/wiki/Examples#List_contents_of_Archive_stored_in_File
1066
1067        my $archive_filename = shift @ARGV;
1068        unless(defined $archive_filename)
1069        {
1070          print "usage: $0 archive.tar\n";
1071          exit;
1072        }
1073
1074        my $archive = ArchiveRead->new;
1075        $archive->support_filter_all;
1076        $archive->support_format_all;
1077
1078        my $r = $archive->open_filename($archive_filename, 1024);
1079        die "error opening $archive_filename: ", $archive->error_string
1080          unless $r == ARCHIVE_OK;
1081
1082        my $entry = ArchiveEntry->new;
1083
1084        while($archive->next_header2($entry) == ARCHIVE_OK)
1085        {
1086          print $entry->pathname, "\n";
1087          $archive->data_skip;
1088        }
1089
1090       Discussion: libarchive is the implementation of "tar" for FreeBSD
1091       provided as a library and available on a number of platforms.
1092
1093       One interesting thing about libarchive is that it provides a kind of
1094       object oriented interface via opaque pointers.  This example creates an
1095       abstract class "Archive", and concrete classes "ArchiveWrite",
1096       "ArchiveRead" and "ArchiveEntry".  The concrete classes can even be
1097       inherited from and extended just like any Perl classes because of the
1098       way the custom types are implemented.  We use Platypus's "object" type
1099       for this implementation, which is a wrapper around an "opaque" (can
1100       also be an integer) type that is blessed into a particular class.
1101
1102       Another advanced feature of this example is that we define a mangler to
1103       modify the symbol resolution for each class.  This means we can do this
1104       when we define a method for Archive:
1105
1106        $ffi->attach( support_filter_all => ['archive_t'] => 'int' );
1107
1108       Rather than this:
1109
1110        $ffi->attach(
1111          [ archive_read_support_filter_all => 'support_read_filter_all' ] =>
1112          ['archive_t'] => 'int' );
1113        );
1114
1115   unix open
1116        use FFI::Platypus;
1117
1118        {
1119          package FD;
1120
1121          use constant O_RDONLY => 0;
1122          use constant O_WRONLY => 1;
1123          use constant O_RDWR   => 2;
1124
1125          use constant IN  => bless \do { my $in=0  }, __PACKAGE__;
1126          use constant OUT => bless \do { my $out=1 }, __PACKAGE__;
1127          use constant ERR => bless \do { my $err=2 }, __PACKAGE__;
1128
1129          my $ffi = FFI::Platypus->new( api => 1, lib => [undef]);
1130
1131          $ffi->type('object(FD,int)' => 'fd');
1132
1133          $ffi->attach( [ 'open' => 'new' ] => [ 'string', 'int', 'mode_t' ] => 'fd' => sub {
1134            my($xsub, $class, $fn, @rest) = @_;
1135            my $fd = $xsub->($fn, @rest);
1136            die "error opening $fn $!" if $$fd == -1;
1137            $fd;
1138          });
1139
1140          $ffi->attach( write => ['fd', 'string', 'size_t' ] => 'ssize_t' );
1141          $ffi->attach( read  => ['fd', 'string', 'size_t' ] => 'ssize_t' );
1142          $ffi->attach( close => ['fd'] => 'int' );
1143        }
1144
1145        my $fd = FD->new("$0", FD::O_RDONLY);
1146
1147        my $buffer = "\0" x 10;
1148
1149        while(my $br = $fd->read($buffer, 10))
1150        {
1151          FD::OUT->write($buffer, $br);
1152        }
1153
1154        $fd->close;
1155
1156       Discussion: The Unix file system calls use an integer handle for each
1157       open file.  We can use the same "object" type that we used for
1158       libarchive above, except we let platypus know that the underlying type
1159       is "int" instead of "opaque" (the latter being the default for the
1160       "object" type).  Mainly just for demonstration since Perl has much
1161       better IO libraries, but now we have an OO interface to the Unix IO
1162       functions.
1163
1164   bzip2
1165        use FFI::Platypus 0.20 (); # 0.20 required for using wrappers
1166        use FFI::CheckLib qw( find_lib_or_die );
1167        use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar );
1168        use FFI::Platypus::Memory qw( malloc free );
1169
1170        my $ffi = FFI::Platypus->new( api => 1 );
1171        $ffi->lib(find_lib_or_die lib => 'bz2');
1172
1173        $ffi->attach(
1174          [ BZ2_bzBuffToBuffCompress => 'compress' ] => [
1175            'opaque',                           # dest
1176            'unsigned int *',                   # dest length
1177            'opaque',                           # source
1178            'unsigned int',                     # source length
1179            'int',                              # blockSize100k
1180            'int',                              # verbosity
1181            'int',                              # workFactor
1182          ] => 'int',
1183          sub {
1184            my $sub = shift;
1185            my($source,$source_length) = scalar_to_buffer $_[0];
1186            my $dest_length = int(length($source)*1.01) + 1 + 600;
1187            my $dest = malloc $dest_length;
1188            my $r = $sub->($dest, \$dest_length, $source, $source_length, 9, 0, 30);
1189            die "bzip2 error $r" unless $r == 0;
1190            my $compressed = buffer_to_scalar($dest, $dest_length);
1191            free $dest;
1192            $compressed;
1193          },
1194        );
1195
1196        $ffi->attach(
1197          [ BZ2_bzBuffToBuffDecompress => 'decompress' ] => [
1198            'opaque',                           # dest
1199            'unsigned int *',                   # dest length
1200            'opaque',                           # source
1201            'unsigned int',                     # source length
1202            'int',                              # small
1203            'int',                              # verbosity
1204          ] => 'int',
1205          sub {
1206            my $sub = shift;
1207            my($source, $source_length) = scalar_to_buffer $_[0];
1208            my $dest_length = $_[1];
1209            my $dest = malloc $dest_length;
1210            my $r = $sub->($dest, \$dest_length, $source, $source_length, 0, 0);
1211            die "bzip2 error $r" unless $r == 0;
1212            my $decompressed = buffer_to_scalar($dest, $dest_length);
1213            free $dest;
1214            $decompressed;
1215          },
1216        );
1217
1218        my $original = "hello compression world\n";
1219        my $compressed = compress($original);
1220        print decompress($compressed, length $original);
1221
1222       Discussion: bzip2 is a compression library.  For simple one shot
1223       attempts at compression/decompression when you expect the original and
1224       the result to fit within memory it provides two convenience functions
1225       "BZ2_bzBuffToBuffCompress" and "BZ2_bzBuffToBuffDecompress".
1226
1227       The first four arguments of both of these C functions are identical,
1228       and represent two buffers.  One buffer is the source, the second is the
1229       destination.  For the destination, the length is passed in as a pointer
1230       to an integer.  On input this integer is the size of the destination
1231       buffer, and thus the maximum size of the compressed or decompressed
1232       data.  When the function returns the actual size of compressed or
1233       compressed data is stored in this integer.
1234
1235       This is normal stuff for C, but in Perl our buffers are scalars and
1236       they already know how large they are.  In this sort of situation,
1237       wrapping the C function in some Perl code can make your interface a
1238       little more Perl like.  In order to do this, just provide a code
1239       reference as the last argument to the "attach" method.  The first
1240       argument to this wrapper will be a code reference to the C function.
1241       The Perl arguments will come in after that.  This allows you to modify
1242       / convert the arguments to conform to the C API.  What ever value you
1243       return from the wrapper function will be returned back to the original
1244       caller.
1245
1246   bundle your own code
1247       "ffi/foo.c":
1248
1249        #include <ffi_platypus_bundle.h>
1250        #include <string.h>
1251
1252        typedef struct {
1253          char *name;
1254          int value;
1255        } foo_t;
1256
1257        foo_t*
1258        foo__new(const char *class_name, const char *name, int value)
1259        {
1260          (void)class_name;
1261          foo_t *self = malloc( sizeof( foo_t ) );
1262          self->name = strdup(name);
1263          self->value = value;
1264          return self;
1265        }
1266
1267        const char *
1268        foo__name(foo_t *self)
1269        {
1270          return self->name;
1271        }
1272
1273        int
1274        foo__value(foo_t *self)
1275        {
1276          return self->value;
1277        }
1278
1279        void
1280        foo__DESTROY(foo_t *self)
1281        {
1282          free(self->name);
1283          free(self);
1284        }
1285
1286       "lib/Foo.pm":
1287
1288        package Foo;
1289
1290        use strict;
1291        use warnings;
1292        use FFI::Platypus;
1293
1294        {
1295          my $ffi = FFI::Platypus->new( api => 1 );
1296
1297          $ffi->type('object(Foo)' => 'foo_t');
1298          $ffi->mangler(sub {
1299            my $name = shift;
1300            $name =~ s/^/foo__/;
1301            $name;
1302          });
1303
1304          $ffi->bundle;
1305
1306          $ffi->attach( new =>     [ 'string', 'string', 'int' ] => 'foo_t'  );
1307          $ffi->attach( name =>    [ 'foo_t' ]                   => 'string' );
1308          $ffi->attach( value =>   [ 'foo_t' ]                   => 'int'    );
1309          $ffi->attach( DESTROY => [ 'foo_t' ]                   => 'void'   );
1310        }
1311
1312        1;
1313
1314       You can bundle your own C (or other compiled language) code with your
1315       Perl extension.  Sometimes this is helpful for smoothing over the
1316       interface of a C library which is not very FFI friendly.  Sometimes you
1317       may want to write some code in C for a tight loop.  Either way, you can
1318       do this with the Platypus bundle interface.  See FFI::Platypus::Bundle
1319       for more details.
1320
1321       Also related is the bundle constant interface, which allows you to
1322       define Perl constants in C space.  See FFI::Platypus::Constant for
1323       details.
1324

FAQ

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

CAVEATS

1417       Platypus and Native Interfaces like libffi rely on the availability of
1418       dynamic libraries.  Things not supported include:
1419
1420       Systems that lack dynamic library support
1421           Like MS-DOS
1422
1423       Systems that are not supported by libffi
1424           Like OpenVMS
1425
1426       Languages that do not support using dynamic libraries from other
1427       languages
1428           Like older versions of Google's Go. This is a problem for C / XS
1429           code as well.
1430
1431       Languages that do not compile to machine code
1432           Like .NET based languages and Java.
1433
1434       The documentation has a bias toward using FFI / Platypus with C.  This
1435       is my fault, as my background in mainly in C/C++ programmer (when I am
1436       not writing Perl).  In many places I use "C" as a short form for "any
1437       language that can generate machine code and is callable from C".  I
1438       welcome pull requests to the Platypus core to address this issue.  In
1439       an attempt to ease usage of Platypus by non C programmers, I have
1440       written a number of foreign language plugins for various popular
1441       languages (see the SEE ALSO below).  These plugins come with examples
1442       specific to those languages, and documentation on common issues related
1443       to using those languages with FFI.  In most cases these are available
1444       for easy adoption for those with the know-how or the willingness to
1445       learn.  If your language doesn't have a plugin YET, that is just
1446       because you haven't written it yet.
1447

SUPPORT

1449       IRC: #native on irc.perl.org
1450
1451       (click for instant chat room login)
1452       <http://chat.mibbit.com/#native@irc.perl.org>
1453
1454       If something does not work the way you think it should, or if you have
1455       a feature request, please open an issue on this project's GitHub Issue
1456       tracker:
1457
1458       <https://github.com/perlFFI/FFI-Platypus/issues>
1459

CONTRIBUTING

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

SEE ALSO

1578       NativeCall
1579           Promising interface to Platypus inspired by Perl 6.
1580
1581       FFI::Platypus::Type
1582           Type definitions for Platypus.
1583
1584       FFI::Platypus::Record
1585           Define structured data records (C "structs") for use with Platypus.
1586
1587       FFI::C
1588           Another interface for defining structured data records for use with
1589           Platypus.  Its advantage over FFI::Platypus::Record is that it
1590           supports "union"s and nested data structures.  Its disadvantage is
1591           that it doesn't support passing "struct"s by-value.
1592
1593       FFI::Platypus::API
1594           The custom types API for Platypus.
1595
1596       FFI::Platypus::Memory
1597           Memory functions for FFI.
1598
1599       FFI::CheckLib
1600           Find dynamic libraries in a portable way.
1601
1602       FFI::TinyCC
1603           JIT compiler for FFI.
1604
1605       FFI::Platypus::Lang::C
1606           Documentation and tools for using Platypus with the C programming
1607           language
1608
1609       FFI::Platypus::Lang::CPP
1610           Documentation and tools for using Platypus with the C++ programming
1611           language
1612
1613       FFI::Platypus::Lang::Fortran
1614           Documentation and tools for using Platypus with Fortran
1615
1616       FFI::Platypus::Lang::Go
1617           Documentation and tools for using Platypus with Go
1618
1619       FFI::Platypus::Lang::Pascal
1620           Documentation and tools for using Platypus with Free Pascal
1621
1622       FFI::Platypus::Lang::Rust
1623           Documentation and tools for using Platypus with the Rust
1624           programming language
1625
1626       FFI::Platypus::Lang::ASM
1627           Documentation and tools for using Platypus with the Assembly
1628
1629       Convert::Binary::C
1630           A great interface for decoding C data structures, including
1631           "struct"s, "enum"s, "#define"s and more.
1632
1633       pack and unpack
1634           Native to Perl functions that can be used to decode C "struct"
1635           types.
1636
1637       C::Scan
1638           This module can extract constants and other useful objects from C
1639           header files that may be relevant to an FFI application.  One
1640           downside is that its use may require development packages to be
1641           installed.
1642
1643       Win32::API
1644           Microsoft Windows specific FFI style interface.
1645
1646       Ctypes <https://gitorious.org/perl-ctypes>
1647           Ctypes was intended as a FFI style interface for Perl, but was
1648           never part of CPAN, and at least the last time I tried it did not
1649           work with recent versions of Perl.
1650
1651       FFI Older, simpler, less featureful FFI.  It used to be implemented
1652           using FSF's "ffcall".  Because "ffcall" has been unsupported for
1653           some time, I reimplemented this module using FFI::Platypus.
1654
1655       C::DynaLib
1656           Another FFI for Perl that doesn't appear to have worked for a long
1657           time.
1658
1659       C::Blocks
1660           Embed a tiny C compiler into your Perl scripts.
1661
1662       Alien::FFI
1663           Provides libffi for Platypus during its configuration and build
1664           stages.
1665
1666       P5NCI
1667           Yet another FFI like interface that does not appear to be supported
1668           or under development anymore.
1669

ACKNOWLEDGMENTS

1671       In addition to the contributors mentioned below, I would like to
1672       acknowledge Brock Wilcox (AWWAIID) and Meredith Howard (MHOWARD) whose
1673       work on "FFI::Sweet" not only helped me get started with FFI but
1674       significantly influenced the design of Platypus.
1675
1676       Dan Book, who goes by Grinnz on IRC for answering user questions about
1677       FFI and Platypus.
1678
1679       In addition I'd like to thank Alessandro Ghedini (ALEXBIO) whose work
1680       on another Perl FFI library helped drive some of the development ideas
1681       for FFI::Platypus.
1682

AUTHOR

1684       Author: Graham Ollis <plicease@cpan.org>
1685
1686       Contributors:
1687
1688       Bakkiaraj Murugesan (bakkiaraj)
1689
1690       Dylan Cali (calid)
1691
1692       pipcet
1693
1694       Zaki Mughal (zmughal)
1695
1696       Fitz Elliott (felliott)
1697
1698       Vickenty Fesunov (vyf)
1699
1700       Gregor Herrmann (gregoa)
1701
1702       Shlomi Fish (shlomif)
1703
1704       Damyan Ivanov
1705
1706       Ilya Pavlov (Ilya33)
1707
1708       Petr Pisar (ppisar)
1709
1710       Mohammad S Anwar (MANWAR)
1711
1712       Håkon Hægland (hakonhagland, HAKONH)
1713
1714       Meredith (merrilymeredith, MHOWARD)
1715
1716       Diab Jerius (DJERIUS)
1717
1719       This software is copyright (c) 2015,2016,2017,2018,2019,2020 by Graham
1720       Ollis.
1721
1722       This is free software; you can redistribute it and/or modify it under
1723       the same terms as the Perl 5 programming language system itself.
1724
1725
1726
1727perl v5.32.0                      2020-09-21                  FFI::Platypus(3)
Impressum