• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

corpus/H28-Oct-2021-975757

examples/H28-Oct-2021-1,4511,004

ffi/H28-Oct-2021-195154

inc/H28-Oct-2021-2,5361,848

include/H28-Oct-2021-20,2497,297

lib/FFI/H28-Oct-2021-15,1844,264

maint/H28-Oct-2021-456361

t/H28-Oct-2021-11,5938,915

xs/H28-Oct-2021-4,6934,064

xt/H28-Oct-2021-380305

CONTRIBUTINGH A D28-Oct-20215.2 KiB12496

ChangesH A D28-Oct-202133.7 KiB903709

Changes.FFI-BuildH A D28-Oct-20211.2 KiB4330

Changes.FFI-Platypus-Type-StringArrayH A D28-Oct-2021250 106

INSTALLH A D28-Oct-20212.4 KiB7648

LICENSEH A D28-Oct-202118 KiB380292

MANIFESTH A D28-Oct-20217.8 KiB340339

META.jsonH A D28-Oct-20218.2 KiB191189

META.ymlH A D28-Oct-20211.8 KiB7069

Makefile.PLH A D28-Oct-20215.1 KiB9693

READMEH A D28-Oct-202165.6 KiB1,9141,355

SUPPORTH A D28-Oct-2021352 148

author.ymlH A D28-Oct-20213.2 KiB190188

dist.iniH A D28-Oct-20218.1 KiB269236

perlcriticrcH A D28-Oct-20211.9 KiB5956

README

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