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