1FFI::Platypus::Type(3)User Contributed Perl DocumentationFFI::Platypus::Type(3)
2
3
4

NAME

6       FFI::Platypus::Type - Defining types for FFI::Platypus
7

VERSION

9       version 1.32
10

SYNOPSIS

12       OO Interface:
13
14        use FFI::Platypus;
15        my $ffi = FFI::Platypus->new( api => 1 );
16        $ffi->type('int' => 'my_int');
17

DESCRIPTION

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

TYPE CATEGORIES

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

SEE ALSO

1222       FFI::Platypus
1223           Main platypus documentation.
1224
1225       FFI::Platypus::API
1226           Custom types API.
1227
1228       FFI::Platypus::Type::StringPointer
1229           String pointer type.
1230

AUTHOR

1232       Author: Graham Ollis <plicease@cpan.org>
1233
1234       Contributors:
1235
1236       Bakkiaraj Murugesan (bakkiaraj)
1237
1238       Dylan Cali (calid)
1239
1240       pipcet
1241
1242       Zaki Mughal (zmughal)
1243
1244       Fitz Elliott (felliott)
1245
1246       Vickenty Fesunov (vyf)
1247
1248       Gregor Herrmann (gregoa)
1249
1250       Shlomi Fish (shlomif)
1251
1252       Damyan Ivanov
1253
1254       Ilya Pavlov (Ilya33)
1255
1256       Petr Pisar (ppisar)
1257
1258       Mohammad S Anwar (MANWAR)
1259
1260       Håkon Hægland (hakonhagland, HAKONH)
1261
1262       Meredith (merrilymeredith, MHOWARD)
1263
1264       Diab Jerius (DJERIUS)
1265
1267       This software is copyright (c) 2015,2016,2017,2018,2019,2020 by Graham
1268       Ollis.
1269
1270       This is free software; you can redistribute it and/or modify it under
1271       the same terms as the Perl 5 programming language system itself.
1272
1273
1274
1275perl v5.32.0                      2020-09-21            FFI::Platypus::Type(3)
Impressum