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