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