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 2.05
10

SYNOPSIS

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

DESCRIPTION

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

SEE ALSO

1228       FFI::Platypus
1229           Main platypus documentation.
1230
1231       FFI::Platypus::API
1232           Custom types API.
1233
1234       FFI::Platypus::Type::StringPointer
1235           String pointer type.
1236

AUTHOR

1238       Author: Graham Ollis <plicease@cpan.org>
1239
1240       Contributors:
1241
1242       Bakkiaraj Murugesan (bakkiaraj)
1243
1244       Dylan Cali (calid)
1245
1246       pipcet
1247
1248       Zaki Mughal (zmughal)
1249
1250       Fitz Elliott (felliott)
1251
1252       Vickenty Fesunov (vyf)
1253
1254       Gregor Herrmann (gregoa)
1255
1256       Shlomi Fish (shlomif)
1257
1258       Damyan Ivanov
1259
1260       Ilya Pavlov (Ilya33)
1261
1262       Petr Písař (ppisar)
1263
1264       Mohammad S Anwar (MANWAR)
1265
1266       Håkon Hægland (hakonhagland, HAKONH)
1267
1268       Meredith (merrilymeredith, MHOWARD)
1269
1270       Diab Jerius (DJERIUS)
1271
1272       Eric Brine (IKEGAMI)
1273
1274       szTheory
1275
1276       José Joaquín Atria (JJATRIA)
1277
1278       Pete Houston (openstrike, HOUSTON)
1279
1281       This software is copyright (c) 2015-2022 by Graham Ollis.
1282
1283       This is free software; you can redistribute it and/or modify it under
1284       the same terms as the Perl 5 programming language system itself.
1285
1286
1287
1288perl v5.36.0                      2022-11-18            FFI::Platypus::Type(3)
Impressum