1FFI::Platypus::Type(3)User Contributed Perl DocumentationFFI::Platypus::Type(3)
2
3
4
6 FFI::Platypus::Type - Defining types for FFI::Platypus
7
9 version 0.94
10
12 OO Interface:
13
14 use FFI::Platypus;
15 my $ffi = FFI::Platypus->new;
16 $ffi->type('int' => 'my_int');
17
19 This document describes how to define types using FFI::Platypus. Types
20 may be "defined" ahead of time, or simply used when defining or
21 attaching functions.
22
23 # OO example of defining types
24 use FFI::Platypus;
25 my $ffi = FFI::Platypus->new;
26 $ffi->type('int');
27 $ffi->type('string');
28
29 # OO example of simply using types in function declaration or attachment
30 my $f = $ffi->function(puts => ['string'] => 'int');
31 $ffi->attach(puts => ['string'] => 'int');
32
33 Unless you are using aliases the FFI::Platypus#type method is not
34 necessary, but they will throw an exception if the type is incorrectly
35 specified or not supported, which may be helpful.
36
37 Note: This document sometimes uses the term "C Function" as short hand
38 for function implemented in a compiled language. Unless the term is
39 referring literally to a C function example code, you can assume that
40 it should also work with another compiled language.
41
42 meta information about types
43 You can get the size of a type using the FFI::Platypus#sizeof method.
44
45 # OO interface
46 my $intsize = $ffi->sizeof('int');
47 my intarraysize = $ffi->sizeof('int[64]');
48
49 converting types
50 Sometimes it is necessary to convert types. In particular various
51 pointer types often need to be converted for consumption in Perl. For
52 this purpose the FFI::Platypus#cast method is provided. It needs to be
53 used with care though, because not all type combinations are supported.
54 Here are some useful ones:
55
56 # OO interface
57 my $address = $ffi->cast('string' => 'opaque', $string);
58 my $string = $ffi->cast('opaque' => 'string', $pointer);
59
60 aliases
61 Some times using alternate names is useful for documenting the purpose
62 of an argument or return type. For this "aliases" can be helpful. The
63 second argument to the FFI::Platypus#type method can be used to define
64 a type alias that can later be used by function declaration and
65 attachment.
66
67 # OO style
68 use FFI::Platypus;
69 my $ffi = FFI::Platypus->new;
70 $ffi->type('int' => 'myint');
71 $ffi->type('string' => 'mystring');
72 my $f = $ffi->function( puts => ['mystring'] => 'myint' );
73 $ffi->attach( puts => ['mystring'] => 'myint' );
74
75 Aliases are contained without the FFI::Platypus object, so feel free to
76 define your own crazy types without stepping on the toes of other CPAN
77 Platypus developers.
78
80 Native types
81 So called native types are the types that the CPU understands that can
82 be passed on the argument stack or returned by a function. It does not
83 include more complicated types like arrays or structs, which can be
84 passed via pointers (see the opaque type below). Generally native
85 types include void, integers, floats and pointers.
86
87 the void type
88
89 This can be used as a return value to indicate a function does not
90 return a value (or if you want the return value to be ignored).
91
92 integer types
93
94 The following native integer types are always available (parentheticals
95 indicates the usual corresponding C type):
96
97 sint8
98 Signed 8 bit byte ("signed char", "int8_t").
99
100 uint8
101 Unsigned 8 bit byte ("unsigned char", "uint8_t").
102
103 sint16
104 Signed 16 bit integer ("short", "int16_t")
105
106 uint16
107 Unsigned 16 bit integer ("unsigned short", "uint16_t")
108
109 sint32
110 Signed 32 bit integer ("int", "int32_t")
111
112 uint32
113 Unsigned 32 bit integer ("unsigned int", "uint32_t")
114
115 sint64
116 Signed 64 bit integer ("long" or "long long", "int64_t")
117
118 uint64
119 Unsigned 64 bit integer ("unsigned long" or "unsigned long long",
120 "uint64_t")
121
122 You may also use "uchar", "ushort", "uint" and "ulong" as short names
123 for "unsigned char", "unsigned short", "unsigned int" and "unsigned
124 long".
125
126 These integer types are also available, but there actual size and sign
127 may depend on the platform.
128
129 char
130 Somewhat confusingly, "char" is an integer type! This is really an
131 alias for either "sint8_t" or "uint8_t" depending on your platform.
132 If you want to pass a character (not integer) in to a C function
133 that takes a character you want to use the perl ord function. Here
134 is an example that uses the standard libc "isalpha", "isdigit" type
135 functions:
136
137 use FFI::Platypus;
138
139 my $ffi = FFI::Platypus->new;
140 $ffi->lib(undef);
141 $ffi->type('int' => 'character');
142
143 my @list = qw(
144 alnum alpha ascii blank cntrl digit lower print punct
145 space upper xdigit
146 );
147
148 $ffi->attach("is$_" => ['character'] => 'int') for @list;
149
150 my $char = shift(@ARGV) || 'a';
151
152 no strict 'refs';
153 printf "'%s' is %s %s\n", $char, $_, &{'is'.$_}(ord $char) for @list;
154
155 size_t
156 This is usually an "unsigned long", but it is up to the compiler to
157 decide. The "malloc" function is defined in terms of "size_t":
158
159 my $ffi = FFI::Platypus->new;
160 $ffi->attach( malloc => ['size_t'] => 'opaque';
161
162 (Note that you can get "malloc" from FFI::Platypus::Memory).
163
164 There are a number of other types that may or may not be available if
165 they are detected when FFI::Platypus is installed. This includes
166 things like "wchar_t", "off_t", "wint_t". You can use this script to
167 list all the integer types that FFI::Platypus knows about, plus how
168 they are implemented.
169
170 use FFI::Platypus;
171
172 my $ffi = FFI::Platypus->new;
173
174 foreach my $type_name (sort FFI::Platypus->types)
175 {
176 my $meta = $ffi->type_meta($type_name);
177 next unless $meta->{element_type} eq 'int';
178 printf "%20s %s\n", $type_name, $meta->{ffi_type};
179 }
180
181 If you need a common system type that is not provided, please open a
182 ticket in the Platypus project's GitHub issue tracker. Be sure to
183 include the usual header file the type can be found in.
184
185 floating point types
186
187 The following native floating point types are always available
188 (parentheticals indicates the usual corresponding C type):
189
190 float
191 Single precision floating point (float)
192
193 double
194 Double precision floating point (double)
195
196 longdouble
197 Floating point that may be larger than "double" (longdouble). This
198 type is only available if supported by the C compiler used to build
199 FFI::Platypus. There may be a performance penalty for using this
200 type, even if your Perl uses long doubles internally for its number
201 value (NV) type, because of the way FFI::Platypus interacts with
202 "libffi".
203
204 As an argument type either regular number values (NV) or instances
205 of Math::LongDouble are accepted. When used as a return type,
206 Math::LongDouble will be used, if you have that module installed.
207 Otherwise the return type will be downgraded to whatever your
208 Perl's number value (NV) is.
209
210 complex_float
211 Complex single precision floating point (float complex)
212
213 complex_double
214 Complex double precision floating point (double complex)
215
216 "complex_float" and "complex_double" are only available if
217 supported by your C compiler and by libffi. Complex numbers are
218 only supported in very recent versions of libffi, and as of this
219 writing the latest production version doesn't work on x86_64. It
220 does seem to work with the latest production version of libffi on
221 32 bit Intel (x86), and with the latest libffi version in git on
222 x86_64.
223
224 Support for "complex_float", "complex_double" and "longdouble" are
225 limited at the moment. Complex types can only be used as simple
226 arguments (not return types, pointers, arrays or record members) and
227 the "longdouble" can only be used as simple argument or return values
228 (not pointers, arrays or record members). Adding support for these is
229 not difficult, but time consuming, so if you are in need of these
230 features please do not hesitate to open a support ticket on the
231 project's github issue tracker:
232
233 <https://github.com/Perl5-FFI/FFI-Platypus/issues>
234
235 In particular I am hesitant to implementing complex return types, as
236 there are performance and interface ramifications, and I would
237 appreciate talking to someone who is actually going to use these
238 features.
239
240 opaque pointers
241
242 Opaque pointers are simply a pointer to a region of memory that you do
243 not manage, and do not know the structure of. It is like a "void *" in
244 C. These types are represented in Perl space as integers and get
245 converted to and from pointers by FFI::Platypus. You may use "pointer"
246 as an alias for "opaque", although this is discouraged. (The Platypus
247 documentation uses the convention of using "pointer" to refer to
248 pointers to known types (see below) and "opaque" as short hand for
249 opaque pointer).
250
251 As an example, libarchive defines "struct archive" type in its header
252 files, but does not define its content. Internally it is defined as a
253 "struct" type, but the caller does not see this. It is therefore
254 opaque to its caller. There are "archive_read_new" and
255 "archive_write_new" functions to create a new instance of this opaque
256 object and "archive_read_free" and "archive_write_free" to destroy this
257 objects when you are done.
258
259 use FFI::Platypus;
260 my $ffi = FFI::Platypus->new;
261 $lib->find_lib( lib => 'archive' );
262 $ffi->attach(archive_read_new => [] => 'opaque');
263 $ffi->attach(archive_write_new => [] => 'opaque');
264 $ffi->attach(archive_read_free => ['opaque'] => 'int');
265 $ffi->attach(archive_write_free => ['opaque'] => 'int');
266
267 As a special case, when you pass "undef" into a function that takes an
268 opaque type it will be translated into "NULL" for C. When a C function
269 returns a NULL pointer, it will be translated back to "undef".
270
271 There are a number of useful utility functions for dealing with opaque
272 types in the FFI::Platypus::Memory module.
273
274 Strings
275 From the CPU's perspective, strings are just pointers. From Perl and
276 C's perspective, those pointers point to a series of characters. For C
277 they are null terminates ("\0"). FFI::Platypus handles the details
278 where they differ. Basically when you see "char *" or "const char *"
279 used in a C header file you can expect to be able to use the "string"
280 type.
281
282 use FFI::Platypus;
283 my $ffi = FFI::Platypus->new;
284 $ffi->attach( puts => [ 'string' ] => 'int' );
285
286 The pointer passed into C (or other language) is to the content of the
287 actual scalar, which means it can modify the content of a scalar.
288
289 When used as a return type, the string is copied into a new scalar
290 rather than using the original address. This is due to the ownership
291 model of scalars in Perl, but it is also most of the time what you
292 want.
293
294 This can be problematic when a function returns a string that the
295 callee is expected to free. Consider the functions:
296
297 char *
298 get_string()
299 {
300 char *buffer;
301 buffer = malloc(20);
302 strcpy(buffer, "Perl");
303 }
304
305 void
306 free_string(char *buffer)
307 {
308 free(buffer);
309 }
310
311 This API returns a string that you are expected to free when you are
312 done with it. (At least they have provided an API for freeing the
313 string instead of expecting you to call libc free)! A simple binding
314 to get the string would be:
315
316 $ffi->attach( get_string => [] => 'string' ); # memory leak
317 my $str = get_string();
318
319 Which will work to a point, but the memory allocated by get_string will
320 leak. Instead you need to get the opaque pointer, cast it to a string
321 and then free it.
322
323 $ffi->attach( get_string => [] => 'opaque' );
324 $ffi->attach( free_string => ['opaque'] => 'void' );
325 my $ptr = get_string();
326 my $str = $ffi->cast( 'opaque' => 'string' ); # copies the string
327 free_string($ptr);
328
329 If you are doing this sort of thing a lot, it can be worth adding a
330 custom type:
331
332 $ffi->attach( free_string => ['opaque'] => 'void' );
333 $ffi->custom_type( 'my_string' => {
334 native_type => 'opaque',
335 native_to_perl => sub {
336 my($ptr) = @_;
337 my $str = $ffi->cast( 'opaque' => 'string' ); # copies the string
338 free_string($ptr);
339 }
340 });
341
342 $ffi->attach( get_string => [] => 'my_string' );
343 my $str = get_string();
344
345 Since version 0.62, pointers and arrays to strings are supported as a
346 first class type. Prior to that FFI::Platypus::Type::StringArray and
347 FFI::Platypus::Type::StringPointer could be used, though their use in
348 new code is discouraged.
349
350 Strings are not allowed as return types from closure. This, again is
351 due to the ownership model of scalars in Perl. (There is no way for
352 Perl to know when calling language is done with the memory allocated to
353 the string). Consider the API:
354
355 typedef const char *(*get_message_t)(void);
356
357 void
358 print_message(get_message_t get_message)
359 {
360 const char *str;
361 str = get_message();
362 printf("message = %s\n");
363 }
364
365 It feels like this should be able to work:
366
367 $ffi->type('()->string' => 'get_message_t'); # not ok
368 $ffi->attach( print_message => ['get_message_t'] => 'void' );
369 my $get_message = $ffi->closure(sub {
370 return "my message";
371 });
372 print_message($get_message);
373
374 If the type declaration for `get_message_t` were legal, then this
375 script would likely segfault or in the very least corrupt memory. The
376 problem is that once "my message" is returned from the closure Perl
377 doesn't have a reference to it anymore and will free it. To do this
378 safely, you have to keep a reference to the scalar around and return an
379 opaque pointer to the string using a cast.
380
381 $ffi->type('()->opaque' => 'get_message_t');
382 $ffi->attach( print_message => ['get_message_t'] => 'void' );
383 my $get_message => $ffi->closure(sub {
384 our $message = "my message"; # needs to be our so that it doesn't
385 # get free'd
386 my $ptr = $ffi->cast('string' => 'opaque');
387 return $ptr;
388 });
389 print_message($get_message);
390
391 Pointer / References
392 In C you can pass a pointer to a variable to a function in order
393 accomplish the task of pass by reference. In Perl the same is task is
394 accomplished by passing a reference (although you can also modify the
395 argument stack thus Perl supports proper pass by reference as well).
396
397 With FFI::Platypus you can define a pointer types to any of the native
398 types described above (that is all the types we have covered so far
399 except for strings). When using this you must make sure to pass in a
400 reference to a scalar, or "undef" ("undef" will be translated into
401 "NULL").
402
403 If the C code makes a change to the value pointed to by the pointer,
404 the scalar will be updated before returning to Perl space. Example,
405 with C code.
406
407 /* foo.c */
408 void increment_int(int *value)
409 {
410 if(value != NULL)
411 (*value)++;
412 else
413 fprintf(stderr, "NULL pointer!\n");
414 }
415
416 # foo.pl
417 use FFI::Platypus;
418 my $ffi = FFI::Platypus->new;
419 $ffi->lib('libfoo.so'); # change to reflect the dynamic lib
420 # that contains foo.c
421 $ffi->type('int*' => 'int_p');
422 $ffi->attach(increment_int => ['int_p'] => 'void');
423 my $i = 0;
424 increment_int(\$i); # $i == 1
425 increment_int(\$i); # $i == 2
426 increment_int(\$i); # $i == 3
427 increment_int(undef); # prints "NULL pointer!\n"
428
429 Records
430 Records are structured data of a fixed length. In C they are called
431 "struct"s To declare a record type, use "record":
432
433 $ffi->type( 'record (42)' => 'my_record_of_size_42_bytes' );
434
435 The easiest way to mange records with Platypus is by using
436 FFI::Platypus::Record to define a record layout for a record class.
437 Here is a brief example:
438
439 package My::UnixTime;
440
441 use FFI::Platypus::Record;
442
443 record_layout(qw(
444 int tm_sec
445 int tm_min
446 int tm_hour
447 int tm_mday
448 int tm_mon
449 int tm_year
450 int tm_wday
451 int tm_yday
452 int tm_isdst
453 long tm_gmtoff
454 string tm_zone
455 ));
456
457 my $ffi = FFI::Platypus->new;
458 $ffi->lib(undef);
459 # define a record class My::UnixTime and alias it to "tm"
460 $ffi->type("record(My::UnixTime)" => 'tm');
461
462 # attach the C localtime function as a constructor
463 $ffi->attach( localtime => ['time_t*'] => 'tm', sub {
464 my($inner, $class, $time) = @_;
465 $time = time unless defined $time;
466 $inner->(\$time);
467 });
468
469 package main;
470
471 # now we can actually use our My::UnixTime class
472 my $time = My::UnixTime->localtime;
473 printf "time is %d:%d:%d %s\n",
474 $time->tm_hour,
475 $time->tm_min,
476 $time->tm_sec,
477 $time->tm_zone;
478
479 For more detailed usage, see FFI::Platypus::Record.
480
481 Platypus does not manage the structure of a record (that is up to you),
482 it just keeps track of their size and makes sure that they are copied
483 correctly when used as a return type. A record in Perl is just a
484 string of bytes stored as a scalar. In addition to defining a record
485 layout for a record class, there are a number of tools you can use
486 manipulate records in Perl, two notable examples are pack and unpack
487 and Convert::Binary::C.
488
489 Here is an example with commentary that uses Convert::Binary::C to
490 extract the component time values from the C "localtime" function, and
491 then smushes them back together to get the original "time_t" (an
492 integer).
493
494 use Convert::Binary::C;
495 use FFI::Platypus;
496 use Data::Dumper qw( Dumper );
497
498 my $c = Convert::Binary::C->new;
499
500 # Alignment of zero (0) means use
501 # the alignment of your CPU
502 $c->configure( Alignment => 0 );
503
504 # parse the tm record structure so
505 # that Convert::Binary::C knows
506 # what to spit out and suck in
507 $c->parse(<<ENDC);
508 struct tm {
509 int tm_sec;
510 int tm_min;
511 int tm_hour;
512 int tm_mday;
513 int tm_mon;
514 int tm_year;
515 int tm_wday;
516 int tm_yday;
517 int tm_isdst;
518 long int tm_gmtoff;
519 const char *tm_zone;
520 };
521 ENDC
522
523 # get the size of tm so that we can give it
524 # to Platypus
525 my $tm_size = $c->sizeof("tm");
526
527 # create the Platypus instance and create the appropriate
528 # types and functions
529 my $ffi = FFI::Platypus->new;
530 $ffi->lib(undef);
531 $ffi->type("record($tm_size)" => 'tm');
532 $ffi->attach( [ localtime => 'my_localtime' ] => ['time_t*'] => 'tm' );
533 $ffi->attach( [ time => 'my_time' ] => ['tm'] => 'time_t' );
534
535 # ===============================================
536 # get the tm struct from the C localtime function
537 # note that we pass in a reference to the value that time
538 # returns because localtime takes a pointer to time_t
539 # for some reason.
540 my $time_hashref = $c->unpack( tm => my_localtime(\time) );
541
542 # tm_zone comes back from Convert::Binary::C as an opaque,
543 # cast it into a string. We localize it to just this do
544 # block so that it will be a pointer when we pass it back
545 # to C land below.
546 do {
547 local $time_hashref->{tm_zone} = $ffi->cast(opaque => string => $time_hashref->{tm_zone});
548 print Dumper($time_hashref);
549 };
550
551 # ===============================================
552 # convert the tm struct back into an epoch value
553 my $time = my_time( $c->pack( tm => $time_hashref ) );
554
555 print "time = $time\n";
556 print "perl time = ", time, "\n";
557
558 You can also link a record type to a class. It will then be accepted
559 when blessed into that class as an argument passed into a C function,
560 and when it is returned from a C function it will be blessed into that
561 class. Basically:
562
563 $ffi->type( 'record(My::Class)' => 'my_class' );
564 $ffi->attach( my_function1 => [ 'my_class' ] => 'void' );
565 $ffi->attach( my_function2 => [ ] => 'my_class' );
566
567 The only thing that your class MUST provide is either a
568 "ffi_record_size" or "_ffi_record_size" class method that returns the
569 size of the record in bytes.
570
571 Here is a longer practical example, once again using the tm struct:
572
573 package My::UnixTime;
574
575 use FFI::Platypus;
576 use FFI::TinyCC;
577 use FFI::TinyCC::Inline 'tcc_eval';
578
579 # store the source of the tm struct
580 # for repeated use later
581 my $tm_source = <<ENDTM;
582 struct tm {
583 int tm_sec;
584 int tm_min;
585 int tm_hour;
586 int tm_mday;
587 int tm_mon;
588 int tm_year;
589 int tm_wday;
590 int tm_yday;
591 int tm_isdst;
592 long int tm_gmtoff;
593 const char *tm_zone;
594 };
595 ENDTM
596
597 # calculate the size of the tm struct
598 # this time using Tiny CC
599 my $tm_size = tcc_eval qq{
600 $tm_source
601 int main()
602 {
603 return sizeof(struct tm);
604 }
605 };
606
607 # To use My::UnixTime as a record class, we need to
608 # specify a size for the record, a function called
609 # either ffi_record_size or _ffi_record_size should
610 # return the size in bytes. This function has to
611 # be defined before you try to define it as a type.
612 sub _ffi_record_size { $tm_size };
613
614 my $ffi = FFI::Platypus->new;
615 $ffi->lib(undef);
616 # define a record class My::UnixTime and alias it
617 # to "tm"
618 $ffi->type("record(My::UnixTime)" => 'tm');
619
620 # attach the C localtime function as a constructor
621 $ffi->attach( [ localtime => '_new' ] => ['time_t*'] => 'tm' );
622
623 # the constructor needs to be wrapped in a Perl sub,
624 # because localtime is expecting the time_t (if provided)
625 # to come in as the first argument, not the second.
626 # We could also acomplish something similar using
627 # custom types.
628 sub new { _new(\($_[1] || time)) }
629
630 # for each attribute that we are interested in, create
631 # get and set accessors. We just make accessors for
632 # hour, minute and second, but we could make them for
633 # all the fields if we needed.
634 foreach my $attr (qw( hour min sec ))
635 {
636 my $tcc = FFI::TinyCC->new;
637 $tcc->compile_string(qq{
638 $tm_source
639 int
640 get_$attr (struct tm *tm)
641 {
642 return tm->tm_$attr;
643 }
644 void
645 set_$attr (struct tm *tm, int value)
646 {
647 tm->tm_$attr = value;
648 }
649 });
650 $ffi->attach( [ $tcc->get_symbol("get_$attr") => "get_$attr" ] => [ 'tm' ] => 'int' );
651 $ffi->attach( [ $tcc->get_symbol("set_$attr") => "set_$attr" ] => [ 'tm' ] => 'int' );
652 }
653
654 package main;
655
656 # now we can actually use our My::UnixTime class
657 my $time = My::UnixTime->new;
658 printf "time is %d:%d:%d\n", $time->get_hour, $time->get_min, $time->get_sec;
659
660 Contrast a record type which is stored as a scalar string of bytes in
661 Perl to an opaque pointer which is stored as an integer in Perl. Both
662 are treated as pointers in C functions. The situations when you
663 usually want to use a record are when you know ahead of time what the
664 size of the object that you are working with and probably something
665 about its structure. Because a function that returns a structure
666 copies the structure into a Perl data structure, you want to make sure
667 that it is okay to copy the record objects that you are dealing with if
668 any of your functions will be returning one of them.
669
670 Opaque pointers should be used when you do not know the size of the
671 object that you are using, or if the objects are created and free'd
672 through an API interface other than "malloc" and "free".
673
674 Fixed length arrays
675 Fixed length arrays of native types are supported by FFI::Platypus.
676 Like pointers, if the values contained in the array are updated by the
677 C function these changes will be reflected when it returns to Perl
678 space. An example of using this is the Unix "pipe" command which
679 returns a list of two file descriptors as an array.
680
681 use FFI::Platypus;
682
683 my $ffi = FFI::Platypus->new;
684 $ffi->lib(undef);
685 $ffi->attach([pipe=>'mypipe'] => ['int[2]'] => 'int');
686
687 my @fd = (0,0);
688 mypipe(\@fd);
689 my($fd1,$fd2) = @fd;
690
691 print "$fd1 $fd2\n";
692
693 Variable length arrays
694 [version 0.22]
695
696 Variable length arrays are supported for argument types can also be
697 specified by using the "[]" notation but by leaving the size empty:
698
699 $ffi->type('int[]' => 'var_int_array');
700
701 When used as an argument type it will probe the array reference that
702 you pass in to determine the correct size. Usually you will need to
703 communicate the size of the array to the C code. One way to do this is
704 to pass the length of the array in as an additional argument. For
705 example the C code:
706
707 int
708 sum(int *array, int size)
709 {
710 int total, i;
711 for (i = 0, total = 0; i < size; i++)
712 {
713 total += array[i];
714 }
715 return total;
716 }
717
718 Can be called from Perl like this:
719
720 use FFI::Platypus;
721
722 my $ffi = FFI::Platypus->new;
723 $ffi->lib('./var_array.so');
724
725 $ffi->attach( sum => [ 'int[]', 'int' ] => 'int' );
726
727 my @list = (1..100);
728
729 print sum(\@list, scalar @list), "\n";
730
731 Another method might be to have a special value, such as 0 or NULL
732 indicate the termination of the array.
733
734 When a function returns a record type, the value is copied. This is
735 due to the ownership rules of scalars in Perl, and is very similar to
736 the way that strings work. If the function expects you to free the
737 record pointer it returns, then you need to use the opaque type, cast
738 the pointer to a record type and free the pointer. The technique is
739 very similar to the example in the Strings section above.
740
741 Closures
742 A closure (sometimes called a "callback", we use the "libffi"
743 terminology) is a Perl subroutine that can be called from C. In order
744 to be called from C it needs to be passed to a C function. To define
745 the closure type you need to provide a list of argument types and a
746 return type. As of this writing only native types and strings are
747 supported as closure argument types and only native types are supported
748 as closure return types. Here is an example, with C code:
749
750 [ version 0.54 ]
751
752 EXPERIMENTAL: As of version 0.54, the record type (see
753 FFI::Platypus::Record) is also experimentally supported as a closure
754 argument type. One caveat is that the record member type string_rw is
755 NOT supported and probably never will be.
756
757 /*
758 * closure.c - on Linux compile with: gcc closure.c -shared -o closure.so -fPIC
759 */
760
761 #include <stdio.h>
762
763 typedef int (*closure_t)(int);
764 closure_t my_closure = NULL;
765
766 void set_closure(closure_t value)
767 {
768 my_closure = value;
769 }
770
771 int call_closure(int value)
772 {
773 if(my_closure != NULL)
774 return my_closure(value);
775 else
776 fprintf(stderr, "closure is NULL\n");
777 }
778
779 And the Perl code:
780
781 use FFI::Platypus;
782
783 my $ffi = FFI::Platypus->new;
784 $ffi->lib('./closure.so');
785 $ffi->type('(int)->int' => 'closure_t');
786
787 $ffi->attach(set_closure => ['closure_t'] => 'void');
788 $ffi->attach(call_closure => ['int'] => 'int');
789
790 my $closure1 = $ffi->closure(sub { $_[0] * 2 });
791 set_closure($closure1);
792 print call_closure(2), "\n"; # prints "4"
793
794 my $closure2 = $ffi->closure(sub { $_[0] * 4 });
795 set_closure($closure2);
796 print call_closure(2), "\n"; # prints "8"
797
798 If you have a pointer to a function in the form of an "opaque" type,
799 you can pass this in place of a closure type:
800
801 use FFI::Platypus;
802
803 my $ffi = FFI::Platypus->new;
804 $ffi->lib('./closure.so');
805 $ffi->type('(int)->int' => 'closure_t');
806
807 $ffi->attach(set_closure => ['closure_t'] => 'void');
808 $ffi->attach(call_closure => ['int'] => 'int');
809
810 my $closure = $ffi->closure(sub { $_[0] * 6 });
811 my $opaque = $ffi->cast(closure_t => 'opaque', $closure);
812 set_closure($opaque);
813 print call_closure(2), "\n"; # prints "12"
814
815 The syntax for specifying a closure type is a list of comma separated
816 types in parentheticals followed by a narrow arrow "->", followed by
817 the return type for the closure. For example a closure that takes a
818 pointer, an integer and a string and returns an integer would look like
819 this:
820
821 $ffi->type('(opaque, int, string) -> int' => 'my_closure_type');
822
823 Care needs to be taken with scoping and closures, because of the way
824 Perl and C handle responsibility for allocating memory differently.
825 Perl keeps reference counts and frees objects when nothing is
826 referencing them. In C the code that allocates the memory is
827 considered responsible for explicitly free'ing the memory for objects
828 it has created when they are no longer needed. When you pass a closure
829 into a C function, the C code has a pointer or reference to that
830 object, but it has no way up letting Perl know when it is no longer
831 using it. As a result, if you do not keep a reference to your closure
832 around it will be free'd by Perl and if the C code ever tries to call
833 the closure it will probably SIGSEGV. Thus supposing you have a C
834 function "set_closure" that takes a Perl closure, this is almost always
835 wrong:
836
837 set_closure($ffi->closure({ $_[0] * 2 })); # BAD
838
839 In some cases, you may want to create a closure shouldn't ever be
840 free'd. For example you are passing a closure into a C function that
841 will retain it for the lifetime of your application. You can use the
842 sticky method to keep the closure, without the need to keep a reference
843 of the closure:
844
845 {
846 my $closure = $ffi->closure(sub { $_[0] * 2 });
847 $closure->sticky;
848 set_closure($closure); # OKAY
849 }
850 # closure still exists and is accesible from C, but
851 # not from Perl land.
852
853 Custom Types
854 Custom Types in Perl
855
856 Platypus custom types are the rough analogue to typemaps in the XS
857 world. They offer a method for converting Perl types into native types
858 that the "libffi" can understand and pass on to the C code.
859
860 Example 1: Integer constants
861
862 Say you have a C header file like this:
863
864 /* possible foo types: */
865 #define FOO_STATIC 1
866 #define FOO_DYNAMIC 2
867 #define FOO_OTHER 3
868
869 typedef int foo_t;
870
871 void foo(foo_t foo);
872 foo_t get_foo();
873
874 The challenge is here that once the source is processed by the C pre-
875 processor the name/value mappings for these "FOO_" constants are lost.
876 There is no way to fetch them from the library once it is compiled and
877 linked.
878
879 One common way of implementing this would be to create and export
880 constants in your Perl module, like this:
881
882 package Foo;
883
884 use FFI::Platypus;
885 use base qw( Exporter );
886
887 our @EXPORT_OK = qw( FOO_STATIC FOO_DYNAMIC FOO_OTHER foo get_foo );
888
889 use constant FOO_STATIC => 1;
890 use constant FOO_DYNAMIC => 2;
891 use constant FOO_OTHER => 3;
892
893 my $ffi = FFI::Platypus->new;
894 $ffi->attach(foo => ['int'] => 'void');
895 $ffi->attach(get_foo => [] => 'int');
896
897 Then you could use the module thus:
898
899 use Foo qw( foo FOO_STATIC );
900 foo(FOO_STATIC);
901
902 If you didn't want to rely on integer constants or exports, you could
903 also define a custom type, and allow strings to be passed into your
904 function, like this:
905
906 package Foo;
907
908 use FFI::Platypus;
909
910 our @EXPORT_OK = qw( foo get_foo );
911
912 my %foo_types = (
913 static => 1,
914 dynamic => 2,
915 other => 3,
916 );
917 my %foo_types_reverse = reverse %foo_types;
918
919 my $ffi = FFI::Platypus->new;
920 $ffi->custom_type(foo_t => {
921 native_type => 'int',
922 native_to_perl => sub {
923 $foo_types{$_[0]};
924 },
925 perl_to_native => sub {
926 $foo_types_reverse{$_[0]};
927 },
928 });
929
930 $ffi->attach(foo => ['foo_t'] => 'void');
931 $ffi->attach(get_foo => [] => 'foo_t');
932
933 Now when an argument of type "foo_t" is called for it will be converted
934 from an appropriate string representation, and any function that
935 returns a "foo_t" type will return a string instead of the integer
936 representation:
937
938 use Foo;
939 foo('static');
940
941 If the library that you are using has a lot of these constants you can
942 try using Convert::Binary::C or another C header parser to obtain the
943 appropriate name/value pairings for the constants that you need.
944
945 Example 2: Blessed references
946
947 Supposing you have a C library that uses an opaque pointer with a
948 pseudo OO interface, like this:
949
950 typedef struct foo_t;
951
952 foo_t *foo_new();
953 void foo_method(foo_t *, int argument);
954 void foo_free(foo_t *);
955
956 One approach to adapting this to Perl would be to create a OO Perl
957 interface like this:
958
959 package Foo;
960
961 use FFI::Platypus;
962 use FFI::Platypus::API qw( arguments_get_string );
963
964 my $ffi = FFI::Platypus->new;
965 $ffi->custom_type(foo_t => {
966 native_type => 'opaque',
967 native_to_perl => sub {
968 my $class = arguments_get_string(0);
969 bless \$_[0], $class;
970 }
971 perl_to_native => sub { ${$_[0]} },
972 });
973
974 $ffi->attach([ foo_new => 'new' ] => [ 'string' ] => 'foo_t' );
975 $ffi->attach([ foo_method => 'method' ] => [ 'foo_t', 'int' ] => 'void');
976 $ffi->attach([ foo_free => 'DESTROY' ] => [ 'foo_t' ] => 'void');
977
978 my $foo = Foo->new;
979
980 Here we are blessing a reference to the opaque pointer when we return
981 the custom type for "foo_t", and dereferencing that reference before we
982 pass it back in. The function "arguments_get_string" queries the C
983 arguments to get the class name to make sure the object is blessed into
984 the correct class (for more details on the custom type API see
985 FFI::Platypus::API), so you can inherit and extend this class like a
986 normal Perl class. This works because the C "constructor" ignores the
987 class name that we pass in as the first argument. If you have a C
988 "constructor" like this that takes arguments you'd have to write a
989 wrapper for new.
990
991 I good example of a C library that uses this pattern, including
992 inheritance is "libarchive". Platypus comes with a more extensive
993 example in "examples/archive.pl" that demonstrates this.
994
995 Example 3: Pointers with pack / unpack
996
997 TODO
998
999 See example FFI::Platypus::Type::StringPointer.
1000
1001 Example 4: Custom Type modules and the Custom Type API
1002
1003 TODO
1004
1005 See example FFI::Platypus::Type::PointerSizeBuffer.
1006
1007 Example 5: Custom Type on CPAN
1008
1009 You can distribute your own Platypus custom types on CPAN, if you think
1010 they may be applicable to others. The default namespace is prefix with
1011 "FFI::Platypus::Type::", though you can stick it anywhere (under your
1012 own namespace may make more sense if the custom type is specific to
1013 your application).
1014
1015 A good example and pattern to follow is
1016 FFI::Platypus::Type::StringArray.
1017
1018 Custom Types in C/XS
1019
1020 Custom types written in C or XS are a future goal of the FFI::Platypus
1021 project. They should allow some of the flexibility of custom types
1022 written in Perl, with potential performance improvements of native
1023 code.
1024
1026 FFI::Platypus
1027 Main platypus documentation.
1028
1029 FFI::Platypus::API
1030 Custom types API.
1031
1032 FFI::Platypus::Type::StringPointer
1033 String pointer type.
1034
1036 Author: Graham Ollis <plicease@cpan.org>
1037
1038 Contributors:
1039
1040 Bakkiaraj Murugesan (bakkiaraj)
1041
1042 Dylan Cali (calid)
1043
1044 pipcet
1045
1046 Zaki Mughal (zmughal)
1047
1048 Fitz Elliott (felliott)
1049
1050 Vickenty Fesunov (vyf)
1051
1052 Gregor Herrmann (gregoa)
1053
1054 Shlomi Fish (shlomif)
1055
1056 Damyan Ivanov
1057
1058 Ilya Pavlov (Ilya33)
1059
1060 Petr Pisar (ppisar)
1061
1062 Mohammad S Anwar (MANWAR)
1063
1065 This software is copyright (c) 2015,2016,2017,2018,2019 by Graham
1066 Ollis.
1067
1068 This is free software; you can redistribute it and/or modify it under
1069 the same terms as the Perl 5 programming language system itself.
1070
1071
1072
1073perl v5.30.0 2019-07-26 FFI::Platypus::Type(3)